我必須從控制器調用服務功能時管理回調。我的想法是將服務功能包裝在承諾中,但是我不能直接從控制器引用服務功能。相反,我必須創建另一個函數來處理視圖事件。使用AngularJS中的promise來管理控制器的服務回調?
function exampleSrv($q) {
this.exampleFn = function() {
var q = $q.defer();
// Do something
q.resolve();
return q.promise;
};
}
function exampleCtrl(exampleSrv) {
this.exampleFn = exampleSrv.exampleFn;
/* This works but I want to avoid this if possible
this.clickHandler = function() {
this.exampleFn()
.then(function() {
console.log('yay');
})
};
*/
/* And instead do something like this but as a reference not as a call
this.exampleFn()
.then(function() {
console.log('yay');
})
*/
}
有沒有更好的方法來做到這一點?
例子: http://plnkr.co/edit/jg5yoC?p=info