Skip to content Skip to sidebar Skip to footer

Angularjs Custom Directive Fails The Text Box Validation

I have written a custom directive to ensure that a text box can take only integer values. But After using the directive, my $error.required flag always stay false irrespective of

Solution 1:

You code has some flaws, but i think this is because you made the example incorrect, the main issue may be here:

inputName: '=' should be replaced with inputName: '@' to hold the stringvalue of the input name

Solution 2:

I'm not quite sure what's wrong with your example, it just doesn't work... Anyway here's a workaround which you can use to implement your functionality.

HTML:

<divng-app="TextboxExample"ng-controller="ExampleController"><formname="shippingForm"novalidate><inputnumber-only-inputtype="text"name="name"ng-model="testvalue.number"required /><!-- <number-only-input input-value="testvalue.number" input-name="name"/>   --><spanclass="error"ng-show="shippingForm.name.$error.required">
        Please enter a value
    </span></form></div>

Controller:

angular.module('TextboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
       $scope.testvalue = {number: 1, validity: true};
    }])
    .directive('numberOnlyInput', function () {
      return {
          link: function (scope, element, attrs) {
              var watchMe = attrs["ngModel"];
              scope.$watch(watchMe, function(newValue,oldValue) {
                if(newValue == undefined || newValue == null || newValue == ""){
                  return;
                } elseif (isNaN(newValue)) {
                  var myVal = watchMe.split(".");
                  switch (myVal.length) {
                    case1:
                      scope[myVal[0]] = oldValue;
                      break;
                    case2:
                      scope[myVal[0]][myVal[1]] = oldValue;
                  }
                }
              });
          }
      };
  });

Post a Comment for "Angularjs Custom Directive Fails The Text Box Validation"