我必须使用此服务
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 :(得分: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>