angularjs – Angular:使用’@’定义的局部范围属性无法从链接函数访问

前端之家收集整理的这篇文章主要介绍了angularjs – Angular:使用’@’定义的局部范围属性无法从链接函数访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我试图定义一些局部范围属性时,我发现用“@”定义的属性不能直接在链接函数中访问,而那些用“=”或“&”定义的属性不是这种情况.

这是我写的简单指令(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);
                });
            }
        };
});

输出是:

Outside has ‘count’? true

Outside has ‘readonly’? false

Inside has ‘count’? true

Inside has ‘readonly’? true

我不知道为什么scope.readonly(@)没有在范围之外定义.$watch函数虽然不是scope.count(=)的情况?

解决方法

这实际上是从 angular doc引用的预期结果:

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

如果要获取属性的值,可以使用$observe或attrs.readonly:

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

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

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

    ...
}

猜你在找的Angularjs相关文章