簡體   English   中英

從指令中的另一個模塊監視服務的變量

[英]Watch service's variable from another module inside a directive

我有兩個模塊“核心”和“用戶界面”。

ui模塊取決於核心。 這是我的core.js的代碼:

var core = angular.module('core', [ 'ngRoute' ]);

//Services
core.service('httpInformationService', function() {

    this.requestCount = 0;
    this.responseCount = 0;

    this.incrementRequest = function() {
        this.requestCount++;
        console.log('incrementRequest:' + this.requestCount);
    };

    this.incrementReponse = function() {
        this.responseCount++;
    }

    this.decrementRequest = function() {
        this.requestCount--;
        console.log('decrementRequest:' + this.requestCount);
    };

    this.decrementResponse = function() {
        responseCount--;
    }

    this.getRequestCount = function() {
        return requestCount;
    }

    this.getResponseCount = function() {
        return responseCount;
    }
});

//Service provider
core.provider("httpServiceInformationProvider", function() {
    var provider = {};

    provider.$get = ['httpInformationService', function( service ) {
        return service;
    }];

    return provider;
});

//HTTP Interceptor
core.factory('coreHttpInterceptor' ,function( httpInformationService ){
    var coreHttpInterceptor = {
        request: function(config) {
            httpInformationService.incrementRequest();
            return config;
        },
        response: function(response) {
            httpInformationService.decrementRequest();
            return response;
        }
    }

    return coreHttpInterceptor;
});


var config = {
    base_url: enviromnent_url,
}

core.value('config', config);

core.config(function( $interpolateProvider ) {
    $interpolateProvider.startSymbol( "[[" ).endSymbol( "]]" );
});

core.config(function( $httpProvider ) {
   $httpProvider.interceptors.push('coreHttpInterceptor');
});

這是我的ui.js代碼:

 var ui = angular.module('ui',[ 'core' , 'ui.bootstrap' ]);

ui.directive( "shLoadify" , function( httpServiceInformationProvider ){
    return {
        restrict: "AE",
        link: function(scope, element, attrs) {
            element.bind( "click", function() {
                element.text("Loading...");
                element.prop( "disabled", true );
            });
        },
        controller: function($scope) {
            $scope.$watch('httpServiceInformationProvider', function(oldValue, newValue){
                console.log(oldValue + ' ' + newValue);
            }, true);
        }
    }
});

如您所見,我正在嘗試使用$ scope.watch從我的控制器中訪問httpInfomationService的requestCount屬性。

問題是newValue並且oldValue始終為null。 為什么會這樣?

方法1

如果要執行一些動作,當你requestCount變量被改變了這是服務的一部分,你需要broadcast/emit然后你可以通過聽on 但是在這種情況下,您需要在服務中傳遞不建議使用的范圍。

var app = angular.module('app',['app1']);

app.service('myService',function($rootScope){
  this.requestCount=1
  this.incrementRequestCount=function(){ 
    this.requestCount++
    $rootScope.$broadcast('requestCountChanged', { message: this.requestCount });
  }.bind(this)

})


app.controller('myController',['$scope','myService',function($scope,myService){

  $scope.$on('requestCountChanged', function(event, args) {
      // You will find the updated requestCount in args
    }); 

   $scope.click= myService.incrementRequestCount;

}])

var app1 = angular.module('app1',[]);
    app1.controller('mySecondController',['$scope','myService',function($scope,myService){

      $scope.$on('requestCountChanged', function(event, args) {
            // You will find the updated requestCount in args
        }); 

    }])

方法2

沒有通過服務范圍

var app = angular.module('app',['app1']);

app.service('myService',function(){
  this.requestCount=1
  this.incrementRequestCount=function(){ 
    debugger;
    this.requestCount++
  }.bind(this)

})


app.controller('myController',['$scope','myService','$rootScope',function($scope,myService,$rootScope){

   $scope.click=function(){
     myService.incrementRequestCount();
     $rootScope.$broadcast('requestCountChanged', { message: myService.requestCount });

   }  

}])

var app1 = angular.module('app1',[]);
    app1.controller('mySecondController',['$scope','myService',function($scope,myService){

      $scope.$on('requestCountChanged', function(event, args) {

            // You will find the updated requestCount in args
        }); 

    }])

方法3

您只能將watch附加到實際在范圍內的那些屬性,否則就無法監視這些屬性。 因此,只需在您的作用域上添加requestCount ,便可以使用watch輕松檢測其更改,然后使用廣播/發射方法。

var app = angular.module('app',['app1']);

app.service('myService',function(){
  this.requestCount=1
  this.incrementRequestCount=function(){ 
    debugger;
    this.requestCount++
  }.bind(this)

})


app.controller('myController',['$scope','myService','$rootScope',function($scope,myService,$rootScope){

    $scope.requestCount=myService.requestCount
    $scope.$watch('requestCount',function(n,o){
      debugger;
      if(n!=o)
      {
          $rootScope.$broadcast('requestCountChanged', { message: n });
      }
    })
   $scope.click=function(){
     myService.incrementRequestCount();
     $scope.requestCount=myService.requestCount


   }  

}])

var app1 = angular.module('app1',[]);
    app1.controller('mySecondController',['$scope','myService',function($scope,myService){

      $scope.$on('requestCountChanged', function(event, args) {

            // You will find the updated requestCount in args
        }); 

    }])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM