2017-04-13 88 views
0

我必須要使用這項服務

angular.service('KitchenService', function(){ 
    this.lunch = { 
     status : null, 
     ... 
    }; 

    this.lunchIsReady = function(){ 
     if(typeof this.lunch.status === "undefined") 
      return null; 
     else    
      return this.lunch.status; 
    } 

    this.lunchEvaluated = function(lunchStatus){ 
     this.lunch.status = lunchStatus; 
     $scope.$root.$emit('KitchenServiceEvent:lunch-status-evaluated'); 
    } 
}); 

在某個時間,某個組件可以稱之爲this.lunchEvaluated因爲它剛剛評估午餐狀態。

所以我發展我的控制器,因爲這:

... 
if(KitchenService.lunchIsReady() == null) 
    $scope.$root.$on('KitchenServiceEvent:lunch-status-evaluated', function(){ 
     if(KitchenService.lunchIsReady()) 
      takeASeatAtTheTable(); 
    }); 
else 
    if(KitchenService.lunchIsReady()) 
     takeASeatAtTheTable(); 
... 

控制器需要啓用該事件偵聽器只有在午餐資格尚未可評估。

是否有一種更方便的方法,不需要在所有需要在餐桌旁就餐的控制器中複製此模板,只有在午餐準備就緒或準備就緒後才能使用?

回答

0

你可以爲這個,你可以應用到每個頁面創建指令:

JS

angular.module('app').directive('lunch', lunchReady); 

function lunchReady() { 
    return { 
    restrict: 'E', 
    scope: { 
     isReady: '&' 
    }, 
    transclude: true, 
    template: '<div ng-transclude></div>', 
    controller: ['$scope', 'kitchenService', function($scope, kitchenService) { 
     if (kitchenService.lunchIsReady() == null) { 
     var deregister = $scope.$root.$on('KitchenServiceEvent:lunch-status-evaluated', function() { 
      if (KitchenService.lunchIsReady()) 
      $scope.isReady(); 
     }); 
     } else { 
     $scope.isReady(); 
     } 

     $scope.$on('$destroy', function() { 
     deregister && deregister(); 
     }); 
    }] 
    } 
} 

樣本HTML

<div ng-controller="MyController as vm"> 
    <lunch is-ready="vm.lunchReady()"> 
    other code 
    </lunch> 
</div> 
+0

感謝您的建議。我更喜歡唯一的編程解決方案保持不變的看法。無論如何,您的解決方案可能是\t重構增強的第一步。 –