0

您好我想创建一个自定义指令来进行表单验证。我有一个带有复选框和一些文本字段的表单。我想确保用户不会将任何字段留空。

当用户在按下提交后将表单留空时,我希望指令突出显示红色字段的边框。我的问题是,当我创建一个隔离范围指令时它不起作用。如果不是隔离作用域,则只有一个为空时,所有字段都会变为红色。我怎样才能解决这个问题?

指令.js:

   directive('createprofileformerrormsg', function() {
     return {
              scope:{createprofileformerrormsg:'@'},
    restrict: 'A',
               require: 'ngModel',
    link: function(scope, elem, attr, ngModel) {

        scope.$watch('formErrors', function() {

            if (attr.createprofileformerrormsg == 1) {

                elem.css("border", "red solid 1px");
            }
        });

    }


}
});

表单.html

 <form data-ng-submit="createProfile()">
  Ethnicity:  <select createprofileformerrormsg="{{formErrors.ethnicity}}" data-ng-   

 model="ethnicity"  >
    <option value="Asian">Asian</option>
    <option value="Black">Black</option>
    <option value="Caucasian">Caucasian</option>
    <option value="Hispanic">Hispanic</option>
    <option value="Middle Eastern">Middle Eastern</option>
    <option value="Native American">Native American</option>
    <option value="Other ethnicities">Other ethnicities</option>

</select><br/>
Gender:  <select createprofileformerrormsg="formErrors.ethnicity" data-ng-

model="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>
</form>

控制器.js

  $scope.createProfile = function() {
 if ($scope.ethnicity == null) {
        $scope.formErrors.ethnicity = 1;
        error_count++;
    }
  if ($scope.gender == null) {
        $scope.formErrors.ethnicity = 1;
        error_count++;
    }
}
4

1 回答 1

1

尝试这个:

Javascript

app.controller('MainCtrl', function($scope) {      
  $scope.submit = function() {
    $scope.$broadcast('submit');
  }
})
.directive('highlightOnError', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      scope.$on('submit', function() {
        var border = '';
        if (ngModel.$invalid)
          border = 'red solid 1px';

        element.css('border', border);
      });
    }
  };
});

HTML

<body ng-controller="MainCtrl">
  <form ng-submit="submit()" novalidate>
    <input type="text" ng-model="foo" required highlight-on-error />
    <select ng-model="bar" ng-options="option for option in [1, 2, 3]" 
       required highlight-on-error>
      <option value="">choose a number</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</body>

在这里工作 Plunker 。

于 2013-09-04T03:36:00.547 回答