编程语言
首页 > 编程语言> > javascript-AngularJS对象应独立工作

javascript-AngularJS对象应独立工作

作者:互联网

我有两个都用$http响应初始化的数组对象,但是当我尝试在一个数组中添加(push)时,它将被添加到两个数组中.

我尝试下面的代码:

控制器:

myApp.controller("abc", function($scope, lastday_data){
    $scope.objectiveData = [];
    $scope.doneData = [];

    // call service & get data from server
    lastday_data.getData().then(function(success){
        $scope.objectiveData = success;
        $scope.doneData = success;
        $scope.$digest();  // *---> $digest() used*
    },function(error){
        $scope.objectiveData = null;
        $scope.doneData = null;
    });

    // add task done
    $scope.addTaskDone = function() {
        var p = {"id": 101, "name": "testadd", "check": true};
        $scope.doneData.push(p);
        $scope.textDone = "";
    }
});

服务:-从服务器获取数据

myApp.service("lastday_data", function($http){
    this.getData = function() {
        return new Promise(function(resolve, reject){
            $http({
                method: 'GET',
                url: 'http://localhost/task/index.php/v1/example/users'
            }).then(function (response) {
                if(response.status)
                    resolve(response.data);
                else
                    reject();
            },function (error) {
                reject();
            });
        });
    }
});

问题:当我尝试调用控制器的addTaskDone()方法时,该方法在doneData数组中添加了一个对象,但是该对象也被添加到了objectData中.

解决方法:

问题

$scope.objectiveData和$scope.doneData都引用相同的变量成功,因此,如果您更改一个变量,那么另一个也将更改.

通过获取成功的独立副本,使$scope.objectiveData和$scope.doneData引用独立变量.你可以用这个

纯JavaScript

> Array.prototype.slice:$scope.doneData = success.slice();
> Array.prototype.concat:$scope.doneData = [] .concat(成功);
> Array.from:$scope.doneData = Array.from(成功);
> Object.assign:$scope.doneData = Object.assign([],成功);

AngularJS内置函数

> angular.copy:$scope.doneData = angular.copy(成功);
> angular.extend:$scope.doneData = angular.extend([],成功);
> angular.merge(自1.6.5起不推荐使用,请参见known issues):$scope.doneData = angular.merge([],成功);

其他技巧

> JSON.parse/JSON.stringify [1]

$scope.doneData = JSON.parse(JSON.stringify(成功));

所以代替

$scope.objectiveData = success;
$scope.doneData = success;

做(或任何其他先前的替代方法)

$scope.objectiveData = success.slice(); // get a copy of success
$scope.doneData = success.slice(); // get a copy of success

标签:angularjs,angularjs-scope,javascript
来源: https://codeday.me/bug/20191108/2008411.html