为什么Angular js赋值运算符如下所示在Controller中不起作用?

时间:2014-11-16 16:45:03

标签: angularjs angularjs-controller

我看到一些赋值运算符在AngularJS控制器中不起作用。下面有更多细节......

<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) };
});

为什么

this.someelement = this.element1; 

赋值运算符不起作用?

请参阅此处的代码http://jsfiddle.net/anil614sagar/z1a8ze4b/

2 个答案:

答案 0 :(得分:1)

element1是一个原始人。在控制器初始化时,this.element1未定义,因此this.someelement变为undefined。如果要将两个控制器属性的值映射在一起,则必须使用对象而不是基元来实现,以便原型链可以工作。

This article provides some explanation

答案 1 :(得分:1)

angular.module('calculator', []).controller('DoMath', function ($scope) {


    $scope.$watch('element1', function () {

        this.someelement = this.element1;

    }.bind(this));

    ...

});

Fiddle