我有一个使用 angularjs 完成验证的方法。提交表单时按钮被禁用,并在收到响应后启用。但是按钮未启用。为了禁用按钮,我编写了一条指令。
directives.directive('kcAjaxBtn', function (){
return {
'priority' : 9999,
'restrict' : 'A',
'link' : function(scope, element, attrs) {
element.bind('click', function() {
var currHtml = element.html();
element.attr('disabled', 'disabled').html('Please wait…');
var offMe = scope.$watch(KC_AJAX_COMPLETED, function(){
element.removeAttr('disabled').html(currHtml);
offMe();
});
});
}
}
});
在 services.js 中它是这样的
angular.module('kint.services.general').config([
'$httpProvider',
function($httpProvider){
$httpProvider.interceptors.push(function($q, $rootScope){
return {
'request': function(config) {
return config || $q.when(config);
},
'response' : function(response) {
$rootScope.$broadcast(KC_AJAX_COMPLETE, response);
return response || $q.when(response);
},
'responseError' : function(response) {
$rootScope.$broadcast(KC_AJAX_COMPLETE, response);
switch(response.status) {
case 401:
window.location.reload();
}
return $q.reject(response);
}
};
});
}
]);
但按钮未启用,如果某些字段无效,如何解决?
最佳答案
您正在使用 $broadcast
广播服务中的事件,但 $watch
不用于接收该事件。您需要使用 $on
来接收事件。
此外,在您的指令中,我将注入(inject) $rootScope
。那么就不再需要使用$broadcast
了。您可以使用 $emit
代替。
所以你的指令变成:
directives.directive('kcAjaxBtn', ['$rootScope', function ($rootScope){
return {
'priority' : 9999,
'restrict' : 'A',
'link' : function(scope, element, attrs) {
element.on('click', function() {
var currHtml = element.html();
element.attr('disabled', 'disabled').html('Please wait…');
});
$rootScope.$on(KC_AJAX_COMPLETED, function(){
element.removeAttr('disabled').html(currHtml);
});
}
}
}]);
在您的服务中,使用$emit
:
$rootScope.$emit(KC_AJAX_COMPLETE, response);
注意:这未经测试,您需要确保您的服务确实发出事件(通过调试,例如在 Chrome 开发工具中)。
关于javascript - 字段验证后的 Angular js 切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22036424/