我有一個頁面,其中有一個潛在客戶列表,每個客戶都可以執行某些操作。每個操作都是一個表單,因此可以在同一頁面上多次顯示相同的表單。AngularJs - 向單個控制器發送廣播事件
每個表單都有自己的範圍,它是控制器自己的實例。當表單被提交時,我調用一個服務來完成ajax操作,完成後我廣播一條消息,並在控制器中收聽消息。問題是因爲表單的每個實例都有自己的控制器實例,所以每個表單都會觸發偶數偵聽器。我如何才能將此稱爲主動控制器?下面是一些sampel代碼:
服務:
/**
* Delegate downline submit
*/
delegatedDownlineSubmit(delegateDownLineModel: IDelegateDownLineModel) {
this.PostJson('/api/Lead/DelegateDownLine', delegateDownLineModel)
.success(function (response: IAjaxResponse) {
if (response !== null) {
LeadServices.rootScope.$broadcast('LeadService.DelegatedDownlineSubmitted', response);
}
});
}
控制器 - 形式的每個實例調用一次:
delegateDownLineFormScope.$on('LeadService.DelegatedDownlineSubmitted', function (event: ng.IAngularEvent, ajaxResponse: IAjaxResponse) {
//Do stuff
});
我也打過電話廣播只在範圍:
LeadServices.rootScope.BroadcastToElement('#Lead_123 form[name=DelegateDownLineForm]', 'LeadService.DelegatedDownlineSubmitted', response);
/**
* Broadcast a message to another element on the page
*/
scope.BroadcastToElement = function (selector: any, message: string, ...args: any[]) {
var broadcastArgs = [message];
if (args) {
broadcastArgs = broadcastArgs.concat(args);
}
return angular.element(selector).scope().$broadcast.apply(this, broadcastArgs);
};
在此先感謝您的幫助。
我不知道這是否是最好的解決方案...我會採取任何更好的答案,但現在我已經通過將當前範圍的id作爲額外參數(例如, leadService.delegatedDownlineSubmit(delegateDownLineFormScope.DelegateDownLineModel,delegateDownLineFormScope。$ id); 然後使用該額外參數進行廣播: LeadServices.rootScope。$ broadcast('LeadService.DelegatedDownlineSubmitted'+ scopeId,response); 最後: delegateDownLineFormScope。$ on('LeadService.DelegatedDownlineSubmitted'+ delegateDownLineFormScope。$ id etc – juju 2014-10-28 16:31:26