Reputation: 133
I see some of the assignment operators doesn't work in AngularJS controller.. More details below...
<div ng-app="calculator" ng-init="math.element1=1.2222;math.element2=2.3333" ng-controller="DoMath as math">
<b>Add Two Elements:</b>
<div>
Element 1: <input type="number" min="0" ng-model="math.element1">
</div>
<div>
Element 2: <input type="number" min="0" ng-model="math.element2">
</div>
<div>
<br>Sum (Rounded to two digits):</b> {{math.sum() | number:2 }}
<br>Multiplication (Rounded to two digits):</b> {{math.multiply() | number:2 }}
<br>Division (Rounded to two digits):</b> {{math.divide() | number:2 }}
<br>{{ math.name }} <!-- Prints name -->
<br>{{ math.someelement }} <!-- prints nothing -->
</div>
</div>
angular.module('calculator', [])
.controller('DoMath', function() {
this.name = "hello"; // Works
this.someelement = this.element1; // doesn't work
this.sum = function() { return (this.element1 + this.element2) };
this.multiply = function() { return (this.element1 * this.element2) };
this.divide = function() { return (this.element1 / this.element2) };
});
Why does
this.someelement = this.element1;
assignment operator doesn't work ?
See code in action here http://jsfiddle.net/anil614sagar/z1a8ze4b/
Upvotes: 0
Views: 635
Reputation: 10379
angular.module('calculator', []).controller('DoMath', function ($scope) {
$scope.$watch('element1', function () {
this.someelement = this.element1;
}.bind(this));
...
});
Upvotes: 1
Reputation: 191789
element1
is a primitive. At the time of the Controller's initialization, this.element1
is undefined, so this.someelement
simply becomes undefined
. If you want to map the values of two controller properties together, you have to do so using objects rather than primitives so that the prototype chain works.
This article provides some explanation
Upvotes: 1