Search code examples
javascriptangularjsangularjs-scope

AngularJS objects should work independently


I have 2 array objects both initialized with $http response but when I try to add(push) in one array, it gets added into both.

I tried below code:

Controller:

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

Service: -- get data from the server

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

Problem: when I try to call controller's addTaskDone() method, this method add one object in doneData array but this object get added in objectiveData also.


Solution

  • The problem

    Both $scope.objectiveData and $scope.doneData are referencing the same variable success, so if you change one, the other one is changed too.

    Solution

    Make $scope.objectiveData and $scope.doneData reference independent variables by getting independent copies of success. You can use for this

    Plain JavaScript

    AngularJS builtin functions

    Other tricks

    $scope.doneData = JSON.parse(JSON.stringify(success));

    So instead of

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

    Do (or any other of the previous alternatives)

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