2016-06-16 3 views
0

У меня есть два модуля «core» и «ui».Переменная watch service от другого модуля внутри директивы

Модуль 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); 
     } 
    } 
}); 

Как вы можете видеть, я пытаюсь получить доступ requestCount свойства httpInfomationService внутри моего контроллера с помощью $ scope.watch.

Проблема: newValue и oldValue всегда равны нулю. Почему это так?

+0

Вы смотрите '$' scope.httpInfomationService и неопределен – k102

+0

Когда я пытаюсь войти, он не является. – iamjc015

+0

Нет, вы регистрируете что-то внутри службы. где вы помещаете это в свой объем? – k102

ответ

0

подход 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

Вы можете только приложить часы к тем свойствам, которые на самом деле в рамках иначе вы не можете следить за этими свойствами. Так что просто добавьте requestCount в свой объем, чем вы можете легко обнаружить его изменения с помощью часов, а затем использовать широковещательный/излучательный подход.

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

    }]) 
+0

вы можете предоставить скрипку для этого? Спасибо =) – iamjc015

+0

Просто отредактировал мое сообщение с кодом для вашей справки. –

+0

Уже пробовал это сработало для меня =) Спасибо =) – iamjc015

Смежные вопросы