Angularjs:对象属性值不更新

时间:2017-11-01 04:20:26

标签: javascript angularjs angularjs-scope

我知道有很多与我的问题有关的问题,但我仍然有解决这个问题。我有以下html和JavaScript代码:

<!doctype html>
<html ng-app="Demo">
<head>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">      
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">     
    </script>

</head>
<body ng-controller="AppController">

        <input type="" name="" ng-model="docs[1].value">
        {{m3.value}}
        {{m4}}

    <script type="text/javascript">
        var app = angular.module('Demo', []);

        app.controller(
            "AppController",
            function( $scope ) {

                $scope.docs=[{value:"first doc"}, {value:"second doc"}];                

                $scope.m3=$scope.docs[1]; 
                $scope.m4=$scope.docs[1].value;

            }
        );


    </script>

</body>
</html>

当我输入输入时,m3.value会更新,但m4不会!我无法弄清楚为什么会这样。任何评论表示赞赏。

2 个答案:

答案 0 :(得分:4)

声明1:

$scope.m3=$scope.docs[1];

此语句存储模型docs[1]

的引用

因此,{{m3.value}}将获得更新的模型值。

声明2:

$scope.m4=$scope.docs[1].value; 

此语句复制实际原始值。

所以,{{m4}}仍然是旧值

答案 1 :(得分:1)

好的,所以我解决它的方法是将一个观察者添加到m3.value:

$scope.$watch('m3.value', function(){
     console.log('Changing');
     $scope.m4 = $scope.m3.value;
});

现在$ scope.m4更新。

相关问题