我从自定义指令中得到了一些奇怪的行为。如果我直接传递一个值似乎有效,但是如果我传递一个对值的绑定则无效。另外,当我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属性(attrs.$observe
)的属性(scope.$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