Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: local scope property defined with '@' is not accessible from link function

While I was trying to define some local scope property I found that properties defined with '@' is not accessible directly in the link function while it's not the case for those defined with '=' or '&'

Here is the simple directive I wrote (jsfiddle):

angular.module('test', [])
    .controller('testCtrl', function($scope) {
        $scope.count1 = 5;
    })
    .directive('testDir', function() {
        return {
            restrict: 'A',
            scope: {
                count: '=',
                readonly: '@'
            },
            link: function (scope, elem, attrs) {
            
                console.log('Outside has count? '+('count' in scope));
                console.log('Outside has readonly? '+('readonly' in scope));
            
                scope.$watch('count', function(value){
                    console.log('Inside has count? '+('count' in scope));
                    console.log('Inside has readonly? '+('readonly' in scope));
                    elem.text(value);
                });
            }
        };
});

The output is:

Outside has 'count'? true

Outside has 'readonly'? false

Inside has 'count'? true

Inside has 'readonly'? true

I have no idea why scope.readonly(@) is not defined outside scope.$watch function while it's not the case for scope.count(=)?

like image 684
sliter Avatar asked Jul 31 '13 00:07

sliter


1 Answers

This is actually the expected result, quoted from angular doc:

... during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If you want to get the value of the attribute, you can use $observe or attrs.readonly:

link: function (scope, elem, attrs) {
    ...

    console.log('readonly = ' + attrs.readonly);

    attrs.$observe('readonly', function(value) {
        console.log('readonly = ' + value);
    });

    ...
}
like image 57
Ye Liu Avatar answered Oct 19 '22 15:10

Ye Liu