在angularjs中使用服务时所有控制器中的值更改
问题描述:
正如您所看到的代码,我正在使用服务提取值。我正在使用AnotherCtrl
中的服务获取记录,然后在$scope
中再添加一条记录,该值也在MyCtrl
中更改,但我不想更新MyCtrl
的scope
。在angularjs中使用服务时所有控制器中的值更改
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>
答
UserService是独立的,并因此它会得到更新,你是返回一个对象。如果你不想让那么更新做到这一点
变化
$scope.users = UserService.all();
到
$scope.users = angular.copy(UserService.all());
谢谢只是复制,它的工作,你救我 –
天欢迎您:) Ketan – adutu