Tanase Butcaru
Tanase Butcaru

Reputation: 992

AngularJS - service changes controller data

I discovered that when I call a service method within my controller and pass to it an object as a parameter, any changes that are done to that object (inside service method) are also made to the original object from my controller.

I always thought that controller data should stay unchanged until I changed it inside promise win/error event and only if I need to.

JS sample:

// Code goes here
var app = angular.module('App', []);

app.controller('AppCtrl', function($scope, simpleService){
  $scope.data = { d: 1, c: 10};

  $scope.clickMe = function(){
    simpleService.clickMe($scope.data).then(function(res){
      alert($scope.data.d);
    })
    .catch(function(err){
      alert($scope.data.d);
    });

  }

});

app.factory('simpleService', function($q){
  var simpleServiceMethods = {};

  simpleServiceMethods.clickMe = function(data){
    var deffered = $q.defer();
    //data = JSON.parse(JSON.stringify(data)); - solution: clone data without references

    data.d = 1111;

    deffered.reject();

    return deffered.promise;
  }

  return simpleServiceMethods;
});

Plunker demo: http://plnkr.co/edit/nHz2T7D2mJ0zXWjZZKP3?p=preview

Upvotes: 0

Views: 71

Answers (1)

Jhey
Jhey

Reputation: 1377

I believe this is the nature of angular's databinding. If you want to pass the details of a $scope variable you could make use of angular's cloning capability with copy or update your services to work slightly differently by creating a copy on the service side. Normal CRUD style applications you'd normally be passing the id of an entity, receiving a new entity or posting changes which may in most cases already be present client side.

Upvotes: 0

Related Questions