首页 > 解决方案 > {{}} 内的值未以角度更新

问题描述

有一个我们使用嵌套角度指令的功能。我正在添加一个可以观察行为的简化示例。

这是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变化时,我希望让第二个指令对变化做出反应。

标签: javascriptangularjsangularjs-scopeangularjs-digest

解决方案


将计算移至模板:

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会在下一个摘要周期被观察者覆盖。


推荐阅读