search

Home  >  Q&A  >  body text

angular.js - angularJs的$scope

(1) Two variables are defined in the controller

$scope.a="aaaaa";
$scope.b="bbbbb";

(2) Also define an object to save

$scope.object={
    arr:[$scope.a,$scope.b]
}

(3) Now dynamically modify the values ​​of $scope.a and $scope.b.
But the value in $scope.object.arr has not changed. Why is this? Shouldn't it be updated in real time?

phpcn_u1582phpcn_u15822831 days ago599

reply all(4)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-15 17:07:33

    Because ab都是原始数据类型,在声明object的时候,向arr里填入的就是ab corresponds to the string itself

    So when you modify it later $scope.a$scope.b时,$scope.object it doesn’t change along with it.

    This is like, I have two apples, gave you one, and then I took a bite of mine, because the apples look exactly the same (assuming, it is a false proposition), so I expect that the apple in your hand will also appear A bitten gap.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 17:07:33

    You can use $watch

    $scope.$watch('a',function(v){
        $scope.object.arr
    });
    $scope.$watch('b',function(v){
        $scope.object.arr[1] = v;
    });

    reply
    0
  • 阿神

    阿神2017-05-15 17:07:33

    The default is shallow traversal

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-15 17:07:33

    $scope.a, $scope.b are strings, and assignment is equivalent to directly assigning strings to arrays.
    If you want to achieve your goal, you can monitor a and b. When a and b change, assign a value to the object.

    reply
    0
  • Cancelreply