Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 520
jeffeld Avatar asked Nov 01 '12 16:11

jeffeld


1 Answers

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...

like image 159
Tom Locke Avatar answered Sep 29 '22 07:09

Tom Locke