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

sli*_*ter 5 angularjs angularjs-directive angularjs-scope

当我试图定义一些局部范围属性时,我发现用'@'定义的属性不能直接在链接函数中访问,而对于那些用'='或'&'定义的属性不是这种情况.

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

输出是:

外面有'数'?真正

外面有"只读"吗?假

里面有'数'?真正

里面有"只读"吗?真正

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

Ye *_*Liu 6

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

...在链接阶段,尚未评估插值,因此此时的值设置为未定义.

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

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

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

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

    ...
}
Run Code Online (Sandbox Code Playgroud)