Javascript 如何在angularjs自定义指令中获取模板中的属性值?
我正在尝试获取angularjs中定义为自定义指令的“abc”属性:Javascript 如何在angularjs自定义指令中获取模板中的属性值?,javascript,angularjs,Javascript,Angularjs,我正在尝试获取angularjs中定义为自定义指令的“abc”属性: <div abc="user"> Access granted! </div> 结果应为“user”,但未定义,因为在执行模板时未定义attr。那么,如何解决这个问题,有什么可能的帮助吗?您可以这样做: .directive('abc', function() { return { scope: { attr: '=abc' }, link: fun
<div abc="user">
Access granted!
</div>
结果应为“user”,但未定义,因为在执行模板时未定义attr。那么,如何解决这个问题,有什么可能的帮助吗?您可以这样做:
.directive('abc', function() {
return {
scope: {
attr: '=abc'
},
link: function (scope) {
console.log(scope.attr);
},
template: "" + attr
};
});
您必须扩展范围并在范围中添加属性“attr”
scope: {
attr: '=abc'
}
然后从html中,您可以这样定义属性
<div abc attr="user">
Access granted!
</div>
允许访问!
无法使用从属性加载的动态范围编辑模板,必须使用范围才能更新模板
template: '<div> {{abc}} </div>', // here it's scope.abc
link : function (scope, elem, attr) {
scope.abc = attr.abc;
}
template:'{{abc}}',//这里是scope.abc
链接:功能(范围、要素、属性){
scope.abc=attr.abc;
}
此处控制台显示“attr”未定义!!可以尝试scope.attr
谢谢,我忘了控制台显示的“attr”未定义!!我犯了一个错误尝试这个scopetry控制台。日志(scope)谢谢!根据我函数的逻辑,如何不返回任何模板,从而可以看到原始的“授权访问”呢?这真是一种神奇的方法。帮我解决了我的问题。非常感谢!顺便说一句,有没有其他方法可以不必将其分配给作用域就可以做到这一点?
template: '<div> {{abc}} </div>', // here it's scope.abc
link : function (scope, elem, attr) {
scope.abc = attr.abc;
}