2017-10-11 79 views
0

正如您所看到的代碼,我正在使用服務提取值。我正在使用AnotherCtrl中的服務獲取記錄,然後在$scope中再添加一條記錄,該值也在MyCtrl中更改,但我不想更新MyCtrlscope在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>

回答

2

UserService是獨立的,並因此它會得到更新,你是返回一個對象。如果你不想讓那麼更新做到這一點

變化

$scope.users = UserService.all();

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

+0

謝謝只是複製,它的工作,你救我 –

+0

天歡迎您:) Ketan – adutu

相關問題