0

這裏是我的代碼:如何更新服務範圍?

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; 
    }); 

的觀點:

<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> 
按鈕

將在單擊更新控制器的範圍以及服務?我很困惑如何去做這件事。

回答

1

是的,因爲服務中的privateScope$scope.tests指向相同的數組。

如果你想保持它們分開,那麼你應該從服務返回數組的copy

深層複製

 getScope: function() { 
     return angular.copy(privateScope); 
    } 

淺拷貝

 getScope: function() { 
     return privateScope.slice(); 
    }