简体   繁体   中英

Difference when pass primitive types and Objects to Conntrollers

I'm post example, because i'm thinking you are easier understand my question.

I have this HTML markup

<div ng-app="autoDrops" ng-controller="testController as test">
    <div ng-controller="simpleController as simple">
        <a href="" ng-click="test.addValue(value, test.testValue)">Add</a>
        <a href="" ng-click="test.addValue2(value2, test.testValue2)">Add2</a>
    </div>
    <a href="" ng-click="test.addValue(value, test.testValue)">Add</a>
    <a href="" ng-click="test.addValue2(value2, test.testValue2)">Add2</a>
    <p>
        {{test.testValue}}
    </p>  
    <p>
        {{test.testValue2}}
    </p> 
<div>

and my AngularJs controllers defined like this

var autoDrops = angular.module('autoDrops', []);
autoDrops.controller('testController', function ($scope) {
    this.testValue = 0;
    $scope.value = 1;
    this.addValue = function(value, testValue){
        //why function not work, if i remove this?
        testValue = testValue + value;
    }
    $scope.value2 = {value:"1"};
    this.testValue2 = [];

    this.addValue2 = function(value, testValue2){
    //this function work with this?
        testValue2.push(value);
    }
});
autoDrops.controller('simpleController', function ($scope) {
    $scope.value = 1;
    $scope.value2 = {value:"1"};
});

Example you can see jsfiddle

As said @MMHunter this is because in the 1st case you passe a simple value whereas in the secnd case, you pass an array.

Array are passed by reference and value are passed by value.

So if you want to make it works change

  1. this.testValue = 0; to this.t = {testValue : 0};
  2. test.addValue(value, test.testValue) to test.addValue(value, test.t)
  3. And...

this.addValue = function(value, testValue){
  //why function not work, if i remove this?
  testValue = testValue + value;
}

To

this.addValue = function(value, t){
  //why function not work, if i remove this?
  t.testValue = t.testValue + value;
}

当您不使用this ,您没有更新范围变量, this.testValue = 0会覆盖它,因此this.testValue仍将显示0

一种可能的解决方案是您使用对象this来更新值。

this.testValue = testValue + value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM