0

我有一个多页(视图)注册表单,在视图 3 上我有一个带有 ng-pattern 的输入来评估邮政编码。问题是当我切换视图然后使用 ng-pattern 重新访问视图时,输入变得无效。

<input type="text" class="form-control" name="postal" ng-model="user.postal" ng-minlength="1" ng-maxlength="8" maxlength="8" ng-pattern="/(^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$)|(^\d{5}(-\d{4})?$)/gmi" required>

关于为什么这变得无效的任何想法?

4

1 回答 1

0

这是在视图之间切换时维护有效邮政编码和用户名的工作代码片段。我更改了您的模式字符串以使其适合我,但您的可能没问题。我只是想要一些更简单的测试。模式匹配 xxxxx | xxxxx-xxxx 。

用户对象显示在每个视图上。邮政编码仅在有效时显示。

如果您使用的是 ngView,我发现最容易嵌套在控制器中,并从路由配置中删除控制器选项。当 ngview 更新时,它看起来像一个新的控制器被实例化,你得到一个新的范围。您之前的输入会丢失,而且无效:)

var testApp = angular.module("testApp", ['ngRoute']);

testApp.config(['$routeProvider',
  function($routeProvider) {
    //Every View here shares the same controller. ng-view will give you a new controller if you pass it in.
    $routeProvider.when("/view1", {
        //Use TemplateURL instead to reference an extrnal page
        template: '<h2> view 1 </h2><br/>Zip: <input type="text" class="form-control" name="postal" ng-model="user.postal" ng-pattern="/^\\d{5}$|^\\d{5}-\\d{4}$/"  ng-required="!user.postal" /><br/>{{user}}'
          //controller: testCtrl * Maybe this is your issue. *
      })
      .when("/view2", {
        //Use TemplateURL instead to reference an extrnal page
        template: '<h2> view 2 </h2>Name: <input type="text" class="form-control" name="uname" ng-model="user.name" required  />  <br /> {{user}}'
      });
  }
]);

testApp.controller("testCtrl", function($scope, $http) {
  $scope.user = {};

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.1/angular-route.js">
</script>
<div ng-app="testApp">
  <div ng-controller="testCtrl">
    <a href="#view1">  View 1 </a>
    <br/>
    <a href="#view2">  View 2 </a>
    <ng-view></ng-view>
  </div>
</div>

于 2014-10-23T23:26:37.493 回答