0

As you can see code , i am fetching value using service . I am fetching records using service in AnotherCtrl and then add one more record in $scope and that value is also change in MyCtrl, but i don't want to update scope of MyCtrl.

var app = angular.module("MyApp", []);

app.factory("UserService", function() {
  var users = ["Peter", "Daniel", "Nina"];

  return {
    all: function() {
      return users;
    },
    first: function() {
      return users[0];
    }
  };
});

app.controller("MyCtrl", function($scope, UserService) {
debugger;
  $scope.users = UserService.all();  
});

app.controller("AnotherCtrl", function($scope, UserService) {
debugger;
  $scope.firstUser = UserService.all();
  $scope.firstUser.push('chirag');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body ng-app="MyApp">
  <div ng-controller="MyCtrl">
    <ul ng-repeat="user in users">
      <li>{{user}}</li>
    </ul>
    <div class="nested" ng-controller="AnotherCtrl">
      First user: {{firstUser}}
    </div>
  </div>
</body>
Ketan Modi
  • 1,780
  • 1
  • 16
  • 28

1 Answers1

2

UserService is a singleton and you are returning an object so it's going to get updated. If you don't want to get updated then just copy it

Change

$scope.users = UserService.all();

to

$scope.users = angular.copy(UserService.all());

adutu
  • 391
  • 3
  • 8