我有三个建议,虽然都不完美,但它们都能起作用:
创建一个getter方法,返回promise,并使用&
将该方法绑定到指令上
绑定deferred对象而不是promise(丑陋)
当promise解决/被拒绝时广播一个事件
我已经创建了一个包含所有建议的plunker: http://plnkr.co/edit/jsA0PwpQm0xycLclkBU3?p=preview
app.controller('MainCtrl', function($scope,$q,$timeout) {
var deferred = $q.defer();
$scope.promise = deferred.promise;
$scope.deferred = deferred;
$scope.getPromise = function(){
return deferred.promise;
}
$scope.promise.then(function(msg){
$scope.$broadcast('promiseThen',{rejected:false,msg:msg});
},function(msg){
$scope.$broadcast('promiseThen',{rejected:true,msg:msg});
});
$timeout(function(){deferred.reject('No reason...');},1500)
});
<div promise-test deferred="deferred" get-promise='getPromise()' ></div>
app.directive('promiseTest',function(){
return {
template:'<div>m1: {{m1}}<br>m2: {{m2}}<br>m3: {{m3}}</div>',
scope:{getPromise:'&',deferred:'='}
,link:function(scope,el,attrs){
scope.m1 = scope.m2 = scope.m3 = 'Waiting...';
scope.getPromise().then(function(msg){
scope.m1 = 'Resolve getPromise: '+msg;
},function(msg){
scope.m1 = 'Reject getPromise: '+msg;
})
scope.deferred.promise.then(function(msg){
scope.m2 = 'Resolved deferred.promise: '+msg
},function(msg){
scope.m2 = 'Rejected deferred.promise: '+msg
});
scope.$on('promiseThen',function(ev,val){
if(val.rejected){
scope.m3 = 'Rejected promiseThen: '+val.msg
}else{
scope.m3 = 'Resolved promiseThen: '+val.msg
}
})
}
}
})