2017-04-17 66 views
0

我有以下代码

var myapp = angular.module('myapp', []); 
myapp.controller('FirstCtrl', function ($scope) { 
$scope.people = [ 
    { id: 1, first: 'John', last: 'Rambo' }, 
    { id: 2, first: 'Rocky', last: 'Balboa' }, 
    { id: 3, first: 'John', last: 'Kimble' }, 
    { id: 4, first: 'Ben', last: 'Richards' } 
]; 
$scope.updateByReference = function() { 
    var tst = $scope.people; 
    tst = []; 
    console.log($scope.people); 
} 
}); 

我期望$ scope.people有一个新的价值和空数组对象,但它没有被更新更新,这里是小提琴 http://jsfiddle.net/9fR23/409/

回答

1

您的$scope.people是一个对象。当您执行var tst = $scope.people;时,它会将参考复制到tst中。在您执行tst = []后,它会将tst的值(参考改为$scope.people,而不是$scope.people的值)。所以实际上,当你改变整个变量的值时,你只能让他引用另一个对象。

只是做

$scope.people = [];

+0

那么,怎样才能达到我所期望的行为? – Petran

+0

@Petran更新 –

0
var tst = $scope.people; //tst reference is $scope.people. 

因此尖沙咀或$ scope.people所做的任何更改将反映到两个变量。

SOLUTION:

$scope.updateByReference = function() { 
     var tst = JSON.parse(JSON.stringify($scope.people)); 
     tst = []; 
     console.log($scope.people); 
    }