javascript - {{}} 内的值未以角度更新
问题描述
有一个我们使用嵌套角度指令的功能。我正在添加一个可以观察行为的简化示例。
这是HTML:
<body ng-app="myapp">
<div>
This is the first directive
<first-directive my-val="9">
</first-directive>
</div>
</body>
和 JavaScript:
var app = angular.module("myapp",[]);
app.directive("firstDirective",function(){
return {
template:'<second-directive val-new={{myVal}}></second-directive>',
scope:{
myVal:'@'
},
//transclude:true,
link: {
pre:function(scope,elem,attr){
scope.myVal=scope.myVal+"1";
}
}
}
});
app.directive("secondDirective",function(){
return{
scope:{
valNew:'@'
},
link:{
pre:function(scope,elem,attr){
console.log(scope.valNew);
}
}
}
});
在控制台中,我得到了 pre 方法中更新的结果,但在 html 中,我得到了旧值。
控制台打印:“91” html dom 包含:
<second-directive val-new="9" class="ng-isolate-scope"></second-directive>>
请帮助我理解为什么会观察到这种差异以及如何使这两个地方保持一致
编辑
我只是在寻找一种方法来使第二个指令中的范围变量对第一个指令范围的链接变量中所做的更改做出反应。所以在其他地方发生myVal
变化时,我希望让第二个指令对变化做出反应。
解决方案
将计算移至模板:
var app = angular.module("myapp",[]);
app.directive("firstDirective",function(){
return {
̶t̶e̶m̶p̶l̶a̶t̶e̶:̶'̶<̶s̶e̶c̶o̶n̶d̶-̶d̶i̶r̶e̶c̶t̶i̶v̶e̶ ̶v̶a̶l̶-̶n̶e̶w̶=̶{̶{̶m̶y̶V̶a̶l̶}̶}̶>̶<̶/̶s̶e̶c̶o̶n̶d̶-̶d̶i̶r̶e̶c̶t̶i̶v̶e̶>̶'̶
template:'<second-directive val-new="{{myVal+'1'}}"></second-directive>',
scope:{
myVal:'@'
},
//transclude:true,
link: {
pre:function(scope,elem,attr){
̶s̶c̶o̶p̶e̶.̶m̶y̶V̶a̶l̶=̶s̶c̶o̶p̶e̶.̶m̶y̶V̶a̶l̶+̶"̶1̶"̶;̶
}
}
}
});
属性 ( '@'
) 绑定创建一个观察者,该观察者在每个摘要周期将值从模板复制到隔离范围。preLink 函数中的修改scope.myVal
会在下一个摘要周期被观察者覆盖。
推荐阅读
- node.js - Nodemailer 抛出错误 Invalid login: 534-5.7.14
- vba - 如果我不选择单元格,图表将不起作用
- scala - 为什么我不能在 Scala 中将 String 的实例转换为 Iterable[Char]
- java - 使用 selenium(java) 和 fiddler 模拟 API
- python - 是否可以从python中的集合中丢弃数字字符串(仅包含数字的字符串)?
- python-3.x - Python递归图遍历拒绝工作并给出运行时错误
- ios - swift 4中变量的密码加密
- swift - Swift:扩展序列,其中 Iterator.Element 是泛型类型
- css - CSS 位置属性说明
- ionic3 - Ionic 3:社交分享中的深层链接不起作用