Dan*_*iel 14 angularjs angularjs-scope
是否有一种很好的方法让AngularJS指令评估作为参数传入的属性?
这是一个简单的例子来显示我的问题(我认识到你可以在没有指令的情况下实现这种行为):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望该指令使用值teacher.email(注意链接函数具有正确的值scope.$parent.teacher)而不是字符串teacher.email.
Mar*_*cok 22
正如@Ajay已经在评论中提到的那样,你可以使用scope.recipient.这是有效的,因为您在指令中创建了一个隔离范围:
scope: {
recipient: "="
},
Run Code Online (Sandbox Code Playgroud)
这将创建一个命名范围属性named recipient,它是对父范围属性的双向数据绑定.哪个父母财产?由您的属性定义的那个:recipient="teacher.email"- 因此父范围属性teacher.email被绑定以隔离范围属性recipient.
如果你的指令不会改变它的值recipient,你应该使用'@'而不是'='.'@'给了我们"单向字符串":
scope: {
recipient: "@"
},
Run Code Online (Sandbox Code Playgroud)
您需要更改HTML:
<sendemail recipient="{{teacher.email}}"></sendemail>
Run Code Online (Sandbox Code Playgroud)
在sendEmail()函数中,我们仍然可以使用scope.recipient,就像我们为'='所做的那样.
如果我们scope: true改为使用,该指令将创建一个"普通"子范围,而不是一个隔离范围.在指令中我们将使用
scope.$eval(attrs.recipient)
Run Code Online (Sandbox Code Playgroud)
获得价值.这是因为JavaScript原型继承的工作方式.$ eval将查找属性,teacher.email而不是在指令子范围内找到它.然后它遵循原型链到父作用域并在那里找到它.
| 归档时间: |
|
| 查看次数: |
14091 次 |
| 最近记录: |