Chia Yu Pai

Front-End, HTML5, Javascript, CSS3

Posts match “ $scope ” tag:

Angular Service Event

| Comments

AngularJS 的 Event 模組只能在 controller 中使用
當需要跨越不同的 controller scope 使用時
就無法直接使用內建的 $on, $emit 來實作 Event model
有兩種(或更多)解法來完成這樣的跨 controller 需求

Service variable and $scope.$watch

controller 的 $watch 可以監控 Service 的值
透過 injector service 便可做到不同 controller 之間的訊息溝通

angular.module('testApp')
  .controller('TestCtrl', function ($scope, Watcher) {
    $scope.$watch(function(){
      return Watcher.status;
    }, function (newStatus) {
        if (newStatus === 'done') {
        // ...do something

      }
    });
    // Remember:

    // if you want listen values in object, you have to add third parameter with true.

  )
  .controller('TestCtrl2', function ($scope, Watcher) {
    // ...some async code

    var callback = function () {
        Watcher.status = 'done';
    }
  )
  .service('Watcher', function () {
    this.status = null;
  
    return this;
  });
}

Service Scope

直接建立一個 Scope 來支援內建的 Event model
轉發他的 $on, $emit 來給其他 controller 使用

angular.module('testApp')
  .controller('TestCtrl', function ($scope, Watcher) {
    Watcher.$on('fetched', function () {
        // ...do something

    });
    
    // ...some async code

    var callback = function () {
        Watcher.$emit('fetched');
    }
  )
  .service('Watcher', function ($rootScope) {
    _scope = $rootScope.$new();
    
    this.$on = _scope.$on;
    this.$emit = _scope.$emit;
  
    return this;
  });