Update scope value when service data is changed

后端 未结 6 1242
天命终不由人
天命终不由人 2020-11-27 10:57

I have the following service in my app:

uaInProgressApp.factory(\'uaProgressService\', 
    function(uaApiInterface, $timeout, $rootScope){
        var facto         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 11:26

    Like Gabriel Piacenti said, no watches are needed if you wrap the changing data into an object.

    BUT for updating the changed service data in the scope correctly, it is important that the scope value of the controller that uses the service data does not point directly to the changing data (field). Instead the scope value must point to the object that wraps the changing data.

    The following code should explain this more clear. In my example i use an NLS Service for translating. The NLS Tokens are getting updated via http.

    The Service:

    app.factory('nlsService', ['$http', function($http) {
      var data = {
        get: {
          ressources        : "gdc.ressources",
          maintenance       : "gdc.mm.maintenance",
          prewarning        : "gdc.mobMaint.prewarning",
        }
      };
    // ... asynchron change the data.get = ajaxResult.data... 
      return data;
    }]);
    

    Controller and scope expression

    app.controller('MenuCtrl', function($scope, nlsService)
      {
        $scope.NLS = nlsService;
      }
    );
    
    
    {{NLS.get.maintenance}}

    The above code works, but first i wanted to access my NLS Tokens directly (see the following snippet) and here the values did not become updated.

    app.controller('MenuCtrl', function($scope, nlsService)
      {
        $scope.NLS = nlsService.get;
      }
    );
    
    
    {{NLS.maintenance}}

提交回复
热议问题