当我试图定义一些局部范围属性时,我发现用'@'定义的属性不能直接在链接函数中访问,而用'='或'&'定义的属性不是这种情况。
这是我写的简单指令(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(@)没有在范围之外定义。$ watch函数虽然不是scope.count(=)的情况?
答案 0 :(得分:6)
这实际上是angular doc引用的预期结果:
...在链接阶段,尚未评估插值,因此此时的值设置为未定义。
如果您想获取该属性的值,可以使用$observe
或attrs.readonly
:
link: function (scope, elem, attrs) {
...
console.log('readonly = ' + attrs.readonly);
attrs.$observe('readonly', function(value) {
console.log('readonly = ' + value);
});
...
}