我有以下指令:
app.directive('ngAvatar', function() {
return {
restrict: 'E',
replace: true,
template: '<img class="avatar-medium" ng-src="{{url}}" />',
link: function(scope, elem, attrs) {
console.log(attrs);
var aType = attrs.avatarType;
var aId = attrs.avatarId;
console.log("Type: "+ aType);
console.log("Character ID:"+ aId);
var baseUrl = "http://api-character.com/";
switch(aType){
case "character":
scope.url = baseUrl + "Character/"+aId+"_256.jpg";
}
}
}
});
不幸的是,该指令没有获取指令内的 avatar_id。正如您所看到的,我正在控制台记录属性:
console.log("Type: "+ aType);
console.log("Character ID:"+ aId);
在我看来,我使用这个指令的方式如下:
<ng-avatar avatar_type="character" avatar_id="{{character.character_id}}"></ng-avatar>
以下是我的 Chrome 控制台的输出。正如您所看到的,avatar_id 显示为空白,但在检查 attrs
时,您可以看到该属性存在,但只是没有显示在指令代码中。
Chrome 控制台:
有人知道为什么它不起作用吗?
谢谢
最佳答案
解决这个问题的方法有很多。
使用一次性监视 - 您还可以考虑使用双向绑定(bind)隔离作用域指令
link: function(scope, elem, attrs) {
//Set up watch
var unWatch = scope.$watch(attrs.avatarId, function(v){
if(v){
unWatch();
init();
}
});
function init(){
//initialize here
}
}
并将其绑定(bind)为:
<ng-avatar avatar-type="character" avatar-id="character.character_id"></ng-avatar>
使用属性观察
link: function(scope, elem, attrs) {
//Set up watch
var unWatch = attrs.$observe(attrs.avatarId, function(v){
if(v){
unWatch();
init();
}
});
function init(){
//initialize here
}
}
并使用它
<ng-avatar avatar-type="character" avatar-id="{{character.character_id}}"></ng-avatar>
绑定(bind) promise /数据
app.directive('ngAvatar', function($q) {
//...
link: function(scope, elem, attrs) {
//Set up watch
$q.when(scope.$eval(attrs.character)).then(init);
function init(character){
var id = character.id;
//initialize here
}
}
}
并将其绑定(bind)为
<ng-avatar avatar-type="character" avatar-id="characterPromiseOrCharObject"></ng-avatar>
事件总线
只需使用 Angular 事件总线并从 Controller 广播一个事件,该事件设置数据如char_loaded
,使用scope.$on监听指令中的事件,一旦获得它就初始化。
关于javascript - AngularJS : Directive not picking up attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28080085/