2017-10-11 45 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

相关问题