我尝试创建一个带有验证的表单。我是angular.js的新手。我从示例中复制了一些代码,但是无法正常工作。

这是我的html和脚本:

<body ng-app="myApp">
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <h2>Validation Example</h2>
    <form name="myForm" novalidate>
        <p>Username:<br>
        <input type="text" name="user" ng-model="user" required>
        <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
            <span ng-show="myForm.user.$error.required">Username is required.</span>
        </span>
        </p>

        <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
            <span ng-show="myForm.email.$error.required">Email is required.</span>
            <span ng-show="myForm.email.$error.email">Invalid email address.</span>
        </span>
        </p>

        <label for="password"> Password</label>
        <input type="password" name="password" ng-model="password" placeholder="New Password"/>
        <label for="confirmPassword">Confirm Password</label>
        <input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>
        <span class="error" ng-show="myForm.password.$error.pwmatch"> Passwords don't match. </span>
        <p>
        <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid">
        </p>
    </form>

    <script>
    var app = angular.module('myApp', []);

    app.directive('pwCheck', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                scope.$watch(attrs.pwCheck, function (confirmPassword) {
                    var isValid = ctrl.$viewValue === confirmPassword;
                    ctrl.$setValidity('pwmatch', isValid);
                });
            }
        }
    });
    </script>
</body>


谁能告诉我这是怎么了?

最佳答案

据我对这个指令的了解,@ dcodesmith的解决方案基本上是正确的。试试这个:

<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>


更新。对不起,以前的代码段。看一下这个。这有效:

<input type="password" name="password" ng-model="password" placeholder="New Password"  pw-check="confirmPassword"/>

<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword"/>


JS

link: function (scope, elem, attrs, ctrl) {
  scope.$watch(attrs.pwCheck, function (password) {
    var isValid = ctrl.$viewValue === password;
    ctrl.$setValidity('pwmatch', isValid);
  });
}


JSBin:http://jsbin.com/rakivadibi/1/edit?html,js,output

09-15 13:05