[英]How to call checkbox change event before checked/unchecked in AngularJS?
我在Angular應用中使用angular-bootstrap-switch 。
<input bs-switch ng-model="item.isPublished" type="checkbox" ng-change="vm.handler()">
我想在交換機切換其當前狀態之前調用API。 開關的狀態將根據API的響應而改變。
ng-change
開關狀態后,將調用ng-change
處理程序。 有什么方法可以在狀態更改之前調用處理程序?
為此,您可以使用ng-click
<input bs-switch ng-model="item.isPublished" type="checkbox" ng-click"vm.handler()">
從那里您可以更改模型的價值。
我認為您可以使其更兼容UX
,當您單擊checkbox
它的值將改變,並且switch
狀態也將改變,然后處理對服務器的請求,基於該響應,您必須確定天氣應該是開關在當前狀態與否之間,其他用戶必須等待直到響應完成。
為此,請使用ng-change
<input
bs-switch
ng-model="isSelected"
type="checkbox"
ng-change="processRequest('item.isPublished')"
/>
在控制器中
$scope.processRequest = function(v) {
/*
$http({
method: 'POST',
url: '/someUrl',
data: {},
}).then(function successCallback(response) {
// success callback you decide the switch state is same or not.
}, function errorCallback(response) {
// error call back change the switch state like,
$scope[v] = !$scope[v];
});
*/
//without `$hhtp` i used `$timeout` to get the asynchronous behavior. to demonstrate only, replace with your logic.
$timeout(function() {
console.log($scope[v]);
$scope[v] = !$scope[v];
console.log($scope[v]);
}, 1500);
您需要一個自定義驗證器:
的HTML
<input bs-switch ng-model="item.isPublished" type="checkbox"
my-validator="vm.handler()">
JS
angular.module("myApp").directive('myValidator', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$validators.myValidator =
scope.$eval(attr.myValidator);
}
}
});
有關更多信息,請參見《 AngularJS ngModelController API參考》 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.