2014-09-25 28 views
3

我必須從控制器調用服務功能時管理回調。我的想法是將服務功能包裝在承諾中,但是我不能直接從控制器引用服務功能。相反,我必須創建另一個函數來處理視圖事件。使用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

回答

1

總之,沒有,有沒有更好的方法這個。事實上,這是解決這些問題的建議方式。

0

其實,你可以嘗試這樣的事情:(我有plunker問題,否則將創建一個)

// Example Service 
function exampleSrv($q) { 

    this.exampleFn = function() { 

    var q = $q.defer(); 
    // Do something 
    q.resolve(); 

    return q.promise.then(function() { 

     return { 
     "data": "12345" 
     }; 
    }); 
    }; 
} 

// Example Controller 

function exampleCtrl(exampleSrv) { 

    var ctrl = this; 
    exampleSrv.exampleFn().then(function(data){ 
    ctrl.exampleFn = data; 
    }); 

    /* This works but I want to avoid this 
    this.clickHandler = function() { 

    this.exampleFn() 
     .then(function() { 
      console.log('yay'); 
     }) 
    }; 
*/ 

    /* And instead do something like this 
    this.exampleFn() 
     .then(function() { 
     console.log('yay'); 
     }) 
*/ 
} 

angular.module('example', []) 
    .service('exampleSrv', exampleSrv) 
    .controller('exampleCtrl', exampleCtrl); 

然後在HTML標記,你可以這樣做:

<!DOCTYPE html> 
<html ng-app="example"> 

<head> 
    <script data-require="[email protected]" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="script.js"></script> 
</head> 

<body ng-controller="exampleCtrl as example"> 
    <!-- bind value directly from service --> 
    {{example.exampleFn}} 
</body> 

</html> 

這樣,您不需要額外的控制器功能,並且可以將服務數據直接提供給您的標記。希望這是你正在尋找的。祝你好運。

相關問題