gpt4 book ai didi

javascript - 我如何返回满足指令的 promise ?

转载 作者:行者123 更新时间:2023-12-03 03:56:10 24 4
gpt4 key购买 nike

我有以下代码,并且我已经尝试了所有方法来返回适用于该指令的 promise 。我什至尝试返回响应数据并返回 $q.when(data) 但什么也不返回。我尝试过阅读有关 promise 的内容,这本书与我读过的有所不同。我缺少什么吗?

myApp.controller('smsCtrl', function($scope){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
});
};
})

myApp.directive('onClickDisable', function() {
return {
scope: {
onClickDisable: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
element.prop('disabled',true);
scope.onClickDisable().finally(function() {
element.prop('disabled',false);
})
});
}
};
});

以下html

<div ng-controller="smsCtrl">
<-- field inputs here --></-->
<button type="button" class="btn btn-primary" on-click-disable="sendSMS()">SEND</button>
</div>

JSfiddle Example

最佳答案

无需为此制定特殊指令。只需使用 ng-disabled 和 ng-click 即可:

<div ng-controller="smsCtrl">
<!-- field inputs here -->
<button ng-click="sendSMS()" ng-disabled="pendingSMS">
SEND
</button>
</div>

在 Controller 中:

myApp.controller('smsCtrl', function($scope, serviceNameHere){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
$scope.pendingSMS = true;
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
}).finally(function() {
$scope.pendingSMS = false;
});
};
})

当 SMS 消息开始时, Controller 会设置 pendingSMS 标志以禁用 Send 按钮。服务完成后,该标志将重置并重新启用该按钮。

关于javascript - 我如何返回满足指令的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44937014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com