【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

简单的angular表单验证指令

<html ng-app="myApp">

<head>
  <meta charset="UTF-8">
  <title>test表单验证</title>
  <script type="text/javascript" src="lib/angular/angular.js"></script>
  <script type="text/javascript">
  var app = angular.module('myApp', []);
  app.controller('testCtrl', function($scope) {
    var _test = function() {
      $scope.canSubmit = false;
      console.log('a');
    };

    var init = function() {
      $scope.model = {
        name: 'happen'
      };
      $scope.canSubmit = true;
      $scope.test = _test;
    };
    init();
  });
  app.directive('testValid', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {
        var init = function() {
          elem.on('blur', function() {
            scope.$apply(function() {
              if (elem.val() === 'happen') {
                ctrl.$setValidity('isHappen', false);
              } else {
                ctrl.$setValidity('isHappen', true);
              }

            });

          });
        };
        init();
      }
    }
  });
  </script>
</head>

<body>
  <form name="myForm">
    <div ng-controller="testCtrl">
      <input type="text" name="test" ng-model="model.name" test-valid required>
      <p ng-show="myForm.test.$error.isHappen">名字是默认值</p>
      <p ng-show="myForm.test.$error.required">名字必填项</p>
      <button ng-disabled="myForm.$invalid || !canSubmit" ng-click="test();" style="width: 200px;height: 20px;"></button>
    </div>
  </form>
</body>

</html>

 

posted @ 2016-04-23 11:23  happenzh  阅读(189)  评论(0编辑  收藏  举报