我想在AngularJS中创建一个密码/电子邮件确认指令,但是到目前为止,我所看到的所有指令都依赖于DOM在jQuery中的插入或提取。如果可以的话,我只想依靠$ scope属性。最好的方法是什么?

最佳答案

在研究了实现此类指令的多种有用方法之后,我想出了如何在没有DOM操作或不使用jQuery的情况下执行该指令。这是Plunk that shows how

它涉及使用:

$ scope上两个输入字段上的

  • ng-model属性
  • $ parse(expr)(scope)和一个简单的scope。$ watch表达式-根据添加了match属性指令的控件的$ modelValue在当前范围的上下文中评估“match”属性。
  • 如果基础表单上的$ invalid属性为true,则禁用提交按钮。

  • 我希望这对某些人有用。这是要点:
    var app = angular.module('app', [], function() {} );
    
    app.directive('match', function($parse) {
      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
          scope.$watch(function() {
            return $parse(attrs.match)(scope) === ctrl.$modelValue;
          }, function(currentValue) {
            ctrl.$setValidity('mismatch', currentValue);
          });
        }
      };
    });
    
    app.controller('FormController', function ($scope) {
      $scope.fields = {
        email: '',
        emailConfirm: ''
      };
    
      $scope.submit = function() {
        alert("Submit!");
      };
    });
    

    然后,在HTML中:
    <!DOCTYPE html>
        <html ng-app="app">
          <head lang="en">
            <meta charset="utf-8">
            <title>Custom Plunker</title>
            <link rel="stylesheet" href="style.css">
            <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
            <script src="app.js"></script>
          </head>
          <body ng-controller="FormController">
            <form name='appForm' ng-submit='submit()'>
              <div class="control-group">
                <label class="control-label required" for="email">Email</label>
                <div class="controls">
                  <input id="email" name="email" ng-model="fields.email"
        class="input-xlarge" required="true" type="text" />
                  <p class="help-block">user@example.com</p>
                </div>
              </div>
              <div class="control-group">
                <label class="control-label required" for="emailConfirm">Confirm Email</label>
                <div class="controls">
                  <input name="emailConfirm" ng-model="fields.emailConfirm"
        class="input-xlarge" required="true"
                    type="text" match="fields.email" />
                  <div ng-show="appForm.emailConfirm.$error.mismatch">
                    <span class="msg-error">Email and Confirm Email must match.</span>
                  </div>
                </div>
              </div>
              <button ng-disabled='appForm.$invalid'>Submit</button>
            </form>
          </body>
        </html>
    

    关于javascript - 如何在没有DOM操作或jQuery的情况下在AngularJS中发出指令来验证电子邮件或密码确认?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17475595/

    10-10 00:35
    查看更多