我从自定义指令中得到了一些奇怪的行为。如果我直接传递一个值,它似乎可以工作,但如果我传递一个值的绑定(bind),它就不起作用。另外,我 console.log 时的值似乎是正确的,但它不返回 true。
//directive
angular.module('tallllyApp')
.directive('userColor', ['simpleLogin', '$timeout', function (simpleLogin, $timeout) {
'use strict';
return {
restrict: 'AE',
scope: {
color: '@'
},
link: function(scope, el, attrs) {
el.css('background', '#5DC472');
console.log(attrs); //attrs.color shows 'Andrey'
console.log(attrs.color); //displays nothing
console.log(attrs.color === 'Andrey'); //false
}
};
}]);
//html = {{profile.name}} does output 'Andrey'
<section class="col user-tasks" user-color color="{{profile.name}}">
最佳答案
您的问题很可能是异步分配的profile.name
,当您运行该指令时,数据可能还没有返回。因此,您可以应用的一种技术是通过在范围属性 (scope.$watch
) 的属性 (attrs.$observe
) 上注册监视来等待获取数据>),并在获得值后清理 watch 。
示例:-
link: function(scope, el, attrs) {
el.css('background', '#5DC472');
//attrs.$observe('color', function(v){
var unWatch = scope.$watch('color', function(v){ //Set up a watch
if(v){ //Check if you got the value yet if so
unWatch(); //clear the watch
init(); //initialize directive
}
});
function init(){
console.log(attrs);
console.log(scope.color); //attrs.color
console.log(scope.color === 'Andrey');
}
}
<强> Plnkr
关于javascript - 指令绑定(bind)中的值是正确的,但它没有返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985309/