gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:50:18 24 4
gpt4 key购买 nike

当我尝试定义一些本地范围属性时,我发现用“@”定义的属性无法直接在链接函数中访问,而用“=”或“&”定义的属性则不然

这是我编写的简单指令( 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(@)没有在scope.$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.

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

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

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

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

...
}

关于angularjs - Angular : local scope property defined with '@' is not accessible from link function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com