在angularjs

时间:2017-10-11 14:00:33

标签: jquery angularjs angular-services

正如您可以看到代码,我使用服务获取价值。我使用AnotherCtrl中的服务提取记录,然后在$scope中再添加一条记录,该值也在MyCtrl中更改,但我不想更新{{1} } scope



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




1 个答案:

答案 0 :(得分:2)

UserService是一个单例,您正在返回一个对象,因此它将会更新。如果您不想更新,请将其复制

更改

$scope.users = UserService.all();

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