角度函数在模型更新之前触发:邮政编码检查器

Angular function fires before model is updated: Zipcode checker

本文关键字:邮政编码 检查 函数 模型 更新      更新时间:2023-09-26

似乎在用户的zip绑定到参数之前,checkZip函数正在触发。有没有更好的方法可以使用角度工具完成此操作?我想在用户键入正确的邮政编码后立即启动用户流中的下一步。

.HTML

<input type="text" placeholder="Zipcode" ng-model="zip" ng-change="checkZip('{{zip}}')">

爪哇语

// Zipcode Key
$scope.zipKey = [94203, 94204, 94205];
// Zipcode checker
$scope.checkZip = function(zip) {
    var key = $scope.zipKey;
    if (zip.length == 5) {  
        for(var i = 0;i<key.length;i++) {
            if (key[i] == zip) {
                // Initiate State Change
                $scope.successAlert = 'We serve in your area!';
            }
        }
    }   
}

您最好使用角度表单验证并编写自定义验证器。

这是一篇很棒的文章,涵盖了您需要了解的所有信息。

为了满足您的需求,您可以编写如下指令:

app.directive('ensureZipcode', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, modelController) {
      scope.$watch(attrs.ngModel, function() {
        valid = true // or false, implement your logic here
        modelController.$setValidity('zipcode', valid);
      });
    }
  }
});

这里需要注意:modelController 被设置为 link 函数的第四个参数,因为我们指定了require: 'ngModel'