2017-10-11 5 views
0

코드를 볼 수 있듯이 서비스를 사용하여 값을 가져옵니다. AnotherCtrl에 서비스를 사용하여 레코드를 가져온 다음 $scope에 레코드를 하나 더 추가하고 해당 값도 MyCtrl에서 변경되지만 은 MyCtrl으로 업데이트하고 싶지 않습니다.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

을 저장 :) 케탄 – adutu