5

当我试图定义一些本地范围属性时,我发现用'@'定义的属性不能直接在链接函数中访问,而用'='或'&'定义的那些情况并非如此

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

输出是:

外面有'计数'?真的

外面有'只读'?错误的

里面有'计数'?真的

里面有'只读'?真的

我不知道为什么 scope.readonly(@) 没有在 scope.$watch 函数之外定义,而 scope.count(=) 却不是这样?

4

1 回答 1

6

这实际上是预期的结果,引用自angular doc

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

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

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

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

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

    ...
}
于 2013-07-31T01:21:54.400 回答