有没有一种让 AngularJS 指令评估作为参数传入的属性的好方法?
这是 simplified example显示我的问题(我认识到您可以在没有指令的情况下实现此行为):
link: function postLink(scope, element, attrs) {
debugger; // scope.$parent already knows the value of teacher here
scope.sendEmail = function(){
alert(attrs.recipient);
//window.open("mailto:" + attrs.recipient);
}
}
我希望指令使用
teacher.email
的值(请注意,链接函数的 scope.$parent.teacher
具有正确的值)而不是字符串 teacher.email
.
最佳答案
正如@Ajay 在评论中已经提到的,您可以使用 scope.recipient
.这是有效的,因为您在指令中创建了一个隔离范围:
scope: {
recipient: "="
},
这将创建一个名为
recipient
的指令范围属性。它是双向数据绑定(bind)到父范围属性的。哪个父属性?由您的属性定义的一个:recipient="teacher.email"
– 因此父范围属性 teacher.email
必须隔离范围属性 recipient
.如果你的指令不会改变
recipient
的值,您可能应该使用“@”而不是“=”。 '@' 给了我们“单向字符串”:scope: {
recipient: "@"
},
不过,您需要更改 HTML:
<sendemail recipient="{{teacher.email}}"></sendemail>
在 sendEmail() 函数中,我们仍然可以使用
scope.recipient
,就像我们对'='所做的那样。如果我们使用
scope: true
相反,该指令将创建一个“正常”子范围,而不是隔离范围。在指令中,我们将使用scope.$eval(attrs.recipient)
来获取值(value)。这是因为 JavaScript 原型(prototype)继承的工作方式。 $eval 将寻找属性
teacher.email
而不是在指令子范围内找到它。然后它沿着原型(prototype)链到达父范围并在那里找到它。
关于angularjs - 如何评估指令中的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507233/