包含其他String的字符串不会自动更新

时间:2015-10-20 12:28:19

标签: javascript angularjs

为什么myCtrl.greeting在更新myCtrl.name?

时不会自动更新

angular.module('MyApp', [])
    .controller('MainController', [function(){
        var mCtrl = this;
        mCtrl.name = '';
        mCtrl.greeting = 'Greetings ' + mCtrl.name;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MainController as mCtrl">
    <input type="text" ng-model="mCtrl.name">
    <h3 ng-bind="mCtrl.greeting"></h3>
</div>
    

我认为当我更新mCtrl.name属性时它会运行$ digest循环,然后在视图中更新mCtrl.greeting?

1 个答案:

答案 0 :(得分:2)

这不是因为角度,而是因为JavaScript。在分配greeting - 字符串时,name的值会被复制,而不会被引用。因此即使name发生变化,greeting仍然保持不变。清晰的简短例子:

var a = 'Foo';
var b = a + 'bar'; //b = 'Foobar', there is no reference to a
b == 'Foobar'; //This is true

a = 'Lalelu';
b != 'Lalelubar'; //b is still 'Foobar'

而是在模板中创建表达式以获得所需的行为:

<h3>Greetings {{mCtrl.name}}</h3>

工作正常。试试下面的内容。

&#13;
&#13;
angular.module('MyApp', [])
    .controller('MainController', [function(){
        var mCtrl = this;
        mCtrl.name = '';
        mCtrl.greeting = 'Greetings ' + mCtrl.name;
    }]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MainController as mCtrl">
    <input type="text" ng-model="mCtrl.name">
    <h3>Greetings {{mCtrl.name}}</h3>
</div>
&#13;
&#13;
&#13;