0
正如您所看到的代碼,我正在使用服務提取值。我正在使用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>
謝謝只是複製,它的工作,你救我 –
天歡迎您:) Ketan – adutu