Reputation: 13908
Here is my code:
angular.module("testApp", [])
.service("testService", function() {
var privateScope = [1,2,3];
return {
getScope: function() {
return privateScope;
},
addToScope:function(num) {
privateScope.push(num);
}
}
})
.controller("testCtrl", ["$scope","testService"], function($scope, testService) {
$scope.tests = testService.getScope();
$scope.current = $scope.tests[0];
$scope.addToScope = testService.addtoScope;
});
The View:
<div ng-controller="testCtrl">
<div ng-repeat="num in tests">
<div>{{num}}</div>
</div>
<input type="button" ng-click="addToScope(Math.round(Math.random() * 10))" />
</div>
Will clicking on the button update the scope of the controller as well as the service? I'm very confused as to how to go about doing this.
Upvotes: 0
Views: 43
Reputation: 34288
Yes it well because the privateScope
in the service and $scope.tests
refer to the same array.
If you want to keep them separate, then you should return a copy
of the array from the service.
Deep copy
getScope: function() {
return angular.copy(privateScope);
}
Shallow copy
getScope: function() {
return privateScope.slice();
}
Upvotes: 1