Angular: how to access the directive area of ​​an element in a controller

Given this simple Angular module:

angular.module('fixturesModule', []) .directive('clubfixtures', function () { "use strict"; return { restrict: 'E', replace: true, transclude: true, scope: { club : "@club", max : "@max" }, templateUrl: "ClubResultsTemplate.html", controller: function ($scope, $http) { $http.get("data.json").success(function (data) { $scope.results = data; }); $scope.sortBy = "Date"; } } }); 

How can I access the club and max in the controller function?

Thanks Jeff

+6
source share
2 answers

The 2 mentioned variables ( max and club ) will simply be defined in the area entered in the directory controller. This means that you can write:

 controller: function ($scope, $http) { $scope.max; //do sth with $scope.max $scope.club //so sth with $scope.club $http.get("data.json").success(function (data) { $scope.results = data; }); } 

in your controller.

If you want to read more, I would suggest the "Directive Definition Object" at http://docs.angularjs.org/guide/directive , where it talks about areas in directives.

+5
source

Attributes in the scope specified with '@', as in scope: { myAttr: '@' } get their values ​​after calling the controller function.

You can demonstrate this with a simple setTimeout - see http://jsfiddle.net/Q4seC/ (be sure to open the console)

$ attrs, as you have already found, is ready when you need it.

Interestingly, if you use '=' instead of '@', the value will be ready and available, which makes me think that this can be considered an error in Angular ...

+10
source

All Articles