要解決此問題,請使用publish/subscribe pattern,它允許獲得鬆散耦合架構。
上的AngularJS應用一個偉大的圖書館是postaljs,允許實現了該模式easely:
定義在app.config
,這將是對應用程序的所有地方入店一個$bus
$範圍變量:controlers,指令,...
app.config(function($provide) {
$provide.decorator('$rootScope', [
'$delegate',
function($delegate) {
Object.defineProperty($delegate.constructor.prototype,
'$bus', {
get: function() {
var self = this;
return {
subscribe: function() {
var sub = postal.subscribe.apply(postal, arguments);
self.$on('$destroy',
function() {
sub.unsubscribe();
});
},
channel: function() {
return postal.channel.apply(postal, arguments);
},
publish: function() { postal.publish.apply(postal, arguments); }
};
},
enumerable: false
});
return $delegate;
}
]);
});
發佈
發佈的產品的更新。
var channel = $scope.$bus.channel('myresources');
channel.publish("item.updated", data);
上發佈列表來更新
var channel = $scope.$bus.channel('myresources');
....
channel.publish("list.updated", list);
訂閱 控制器/指令需要被通知用於對 「爲MyResources」 信道的事件。
var channel = $scope.$bus.channel("myresources");
....
//The wildcard * allow be notified on item/list. updated
channel.subscribe("*.updated", function(data, envelopment) {
doOnUpdated();
});
那麼我基本上需要1個控制器的部分怎麼知道如何處理髮射事件呢?有沒有辦法讓它們更通用,所以我可以從HTML模板中控制它們? – shaggeh