我有三个建议 - 没有一个是完美的,但它们都有效:
创建一个返回 promise 的 getter 方法并将此方法绑定到指令使用&
绑定延迟对象而不是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
}
})
}
}
})