自定义验证指令不起作用

时间:2014-09-05 17:31:27

标签: angularjs angularjs-directive

我写了一个简单的指令来验证数字。但是,如果我在输入字段中输入字符,我从未看到错误消息。

http://plnkr.co/edit/pbgVtMI3cT959edrysuA?p=preview

<html ng-app="MyCalc">
  <head>
     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>     
     <script src="app.js"></script>
  </head>
  <body ng-controller="MyController">
    <h4>My Simple Calculator</h4>
    <form name="calcform">
      <span ng-show="calcform.item1.$error.numbersonly">item1 must be a number</span>
      <span ng-show="calcform.item2.$error.numbersonly">item2 must be a number</span>
      <input name="item1" type="number" ng-model="model.item1" numbersonly />            
      <input name="item2" type="number" ng-model="model.item2" numbersonly />
      <input ng-click="add()" type="button" value="+" ng-disabled="calcForm.$invalid"/>
      <input ng-click="subtract()" type="button" value="-" ng-disabled="calcForm.$invalid"/>
      <input ng-click="multiply()" type="button" value="*" ng-disabled="calcForm.$invalid"/>
      <input ng-click="divide()" type="button" value="/" ng-disabled="calcForm.$invalid"/>            
      <p><font size="14">{{model.result}}</font></p>
    </form>
  </body>
</html>

var app = angular.module('MyCalc', []);
app.controller('MyController', function ($scope) {
    var mymodel = { item1: 0, item2: 0, result: 0 };
    $scope.model = mymodel;
    $scope.add = function () { mymodel.result = Number(mymodel.item1) + Number(mymodel.item2); };
    $scope.subtract = function () { mymodel.result = Number(mymodel.item1) - Number(mymodel.item2); };
    $scope.multiply = function () { mymodel.result = Number(mymodel.item1) * Number(mymodel.item2); };
    $scope.divide = function () { mymodel.result = Number(mymodel.item1) / Number(mymodel.item2); };
});

app.directive('numbersonly', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            ctrl.$parsers.unshift(function (value) {
                var isNan = isNaN(value);
                ngModel.$setValidity('numbersonly', !isNan);
                return (!isNan) ? value : undefined;
            });

            ctrl.$formatters.unshift(function (value) {
                var isNan = isNaN(value);
                ngModel.$setValidity('numbersonly', !isNan);
                return value;
            });
    }
  };
});

1 个答案:

答案 0 :(得分:1)

看起来您的指令与内置数字验证冲突。我删除了“type = number”,错误消息显示

            <input name="item1" ng-model="model.item1" numbersonly />            
            <input name="item2"  ng-model="model.item2" numbersonly />

或将其替换为“text”

<input name="item1" type="text" ng-model="model.item1" numbersonly />            
<input name="item2" type="text"  ng-model="model.item2" numbersonly />    

也有效