我试图使用自定义指令更改promise状态上的按钮文本。
这是我的自定义指令的代码
.directive('myDir',function(){
return {
scope: {
myDir: '&',
afterValue: '@',
beforeValue:'@',
ngDisable:'=',
},
link: function ($scope, element, attrs) {
element[0].innerHTML=$scope.beforeValue;
element.bind('click',function(){
console.log(element);
element[0].innerHTML=$scope.afterValue;
element[0].className+="disabled";
element[0].disabled='true'
$scope.myDir();
//success i would like to change the status here
})
}
}
})
和我的控制器
.controller('myCtrl',[function(){
var vm = this;
console.log("MYCTRL");
vm.fun= function(){
//promise running here
}
}])
这里是plnkr链接:https://plnkr.co/edit/Qj9GG2?p=templates/
我无法阅读指令中承诺的成功。
您可以使用.then
来获得promise的结果。在下面的例子中,我创建了一个承诺,该承诺将在2秒钟后得到解决。解决后,指令将更改按钮上的文本。
我用$q
创建了一个promise,但如果您执行ajax调用,情况也是一样的:
vm.fun= function(){
//promise running here
return $http.get('www.foo.org');
}
angular
.module('myApp',[])
.directive('myDir',function(){
return {
scope: {
myDir: '&',
afterValue: '@',
beforeValue:'@',
ngDisable:'=',
},
link: function ($scope, element, attrs) {
element[0].innerHTML=$scope.beforeValue;
element.bind('click',function(){
element[0].innerHTML=$scope.afterValue;
element[0].className+="disabled";
element[0].disabled='true'
$scope.myDir().then(function(){
//success i would like to change the status here
// Change status here...
console.log('Callback from promise. Everything is fine.');
element[0].disabled=false;
element[0].innerHTML = $scope.beforeValue;
}, function(){
// Something went bad.
console.log('Callback from promise. Something went wrong.');
});
})
}
}
})
.controller('myCtrl',['$q', function($q){
var vm = this;
console.log("MYCTRL");
vm.fun= function(){
console.log('method called');
// Create a promise here...
var def = $q.defer();
setTimeout(function(){
console.log('done in controller');
def.resolve();
// You can also use reject if something went wrong.
// def.reject();
}, 2000)
return def.promise;
}
}])
<script data-require="angular.js@1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<div ng-app="myApp">
<div ng-controller="myCtrl as $ctrl">
<button class="btn btn-primary" my-dir="$ctrl.fun()" after-value="Clicked" before-value="click" ng-disabled>Click</button>
</div>
</div>
根据评论更新:
当用户单击按钮时,它应该更改文本并禁用按钮并调用invokepromise。按钮文本更改并禁用i我在指令中执行,并在控制器中调用promise。
这就是$scope.myDir()
行中发生的情况,尽管您没有调用承诺。您调用一个function
,它又返回一个promise
你的意思是应该如何援引承诺
接下来我想根据正在运行的承诺成功或失败在控制器上,我想更改文本并将disable设为false。
这就是.then()
下发生的情况。如果myDir()
成功。然后,代码将更改按钮上的状态。这是在指令中完成的,因为只有指令知道按钮。您从promise中获得了成功和错误回调。