2K01B5
2K01B5

Reputation: 1121

String containing other String not updating automatically

Why doesn't myCtrl.greeting automatically update when I update 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>
    

I thought that when I updated the mCtrl.name property that it would run a $digest loop which would then update mCtrl.greeting in the view?

Upvotes: 1

Views: 34

Answers (1)

LionC
LionC

Reputation: 3106

This is not because of angular, but actually because of JavaScript. When you are assigning your greeting-string, the value of name gets copied, not referenced. So even though name changes, greeting still stays the same. Short example for clarity:

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'

Instead create an expression in your template to get the desired behaviour:

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

Works fine. Try it out below.

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>Greetings {{mCtrl.name}}</h3>
</div>

Upvotes: 2

Related Questions