简体   繁体   中英

Angular: How to access an element directive's scope in the 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 do I access club and max in the controller function?

Thanks, Jeff

Attributes on the scope set up with '@', as in scope: { myAttr: '@' } receive their values after the controller function has been called.

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

$attrs, as you've found, is ready when you need it.

Interestingly, if you use '=' instead of '@', the value is ready and available, which makes me think this could be considered a bug in Angular...

The 2 mentioned variables ( max and club ) will be simply defined in a scope injected to directive's 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 directive's controller.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM