iJa*_*ade 13 javascript angularjs angularjs-directive angularjs-ng-repeat
我试图将$ scope变量值作为属性传递给自定义指令,但它不起作用.
这是HTML代码:
<ul ng-repeat="q in questions">
<li>
{{q.question}}
<check-list name="{{q.id}}"></check-list>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
该指令是<check-list name={{q.id}}></check-list>,这里是指令代码:
app.directive('checkList',function(){
return {
restrict:'E',
template: function(elem,attrs){
console.log(attrs.name);
return '</br> <input type="radio" /> Yes </br> <input type="radio" /> No'
},
link:function(scope,elem,attrs){
}
};
})
Run Code Online (Sandbox Code Playgroud)
我正在记录属性,attrs.name但我得到的值"{{q.id}}"不是实际值q.id
Reb*_*nix 19
我想你想要做的是从控制器向你的指令注入范围对象.所以你可以将你的指令定义为
app.directive('checkList',function(){
return {
restrict:'E',
scope: {
name: "="
}
template: '{{name}}</br> <input type="radio" /> Yes </br> <input type="radio" /> No',
link:function(scope,elem,attrs){
}
};
}
Run Code Online (Sandbox Code Playgroud)
在您看来,您可以将您的指令引用为
<check-list name="q.id"></check-list>
Run Code Online (Sandbox Code Playgroud)
在指令中,属性只是字符串.
在模板函数中,您所能做的就是使用属性的字符串值.如果要使用属性的计算值或插值,可以使用以下几个选项:
1)使用隔离范围
app.directive('checkList', function() {
return {
restrict:'E',
scope: {
name: '&'
}
template: '</br> <input type="radio" /> Yes </br>{{name()}} <input type="radio" /> No'
link: function(scope, elem, attrs) {
}
};
});
<ul ng-repeat="q in questions">
<li>
{{q.question}}
<check-list name="q.id"></check-list>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
2)注入$ interpolate或$ parse以在链接函数中手动评估插值或表达式
app.directive('checkList', function($interpolate) {
return {
restrict:'E',
template: '</br> <input type="radio" /> Yes </br>{{name}} <input type="radio" /> No'
link:function(scope,elem,attrs){
scope.name = $interpolate(attrs.name)(scope);
}
};
});
<ul ng-repeat="q in questions">
<li>
{{q.question}}
<check-list name="{{q.id}}"></check-list>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
2a)最后,$解析
app.directive('checkList',function($parse){
return {
restrict:'E',
template: '</br> <input type="radio" /> Yes </br>{{name}} <input type="radio" /> No'
link:function(scope,elem,attrs){
scope.name = $parse(attrs.name)(scope);
}
};
});
<ul ng-repeat="q in questions">
<li>
{{q.question}}
<check-list name="q.id"></check-list>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)