1

I have created a numberDirective

function numberInputDirective()
 {
    return 
    {
        restrict: 'E',
        scope: 
        {
            model: '=',
            disabled: '=?',
            decimals: '=?',
            form: '=',
            name: '='
        },
        require: '^form',
        replace: true,
        templateUrl: 'directives/pxNumberInput.html',
        link: function (scope, element, attrs, form) 
        {
              scope.inError = function () 
              {
                  return form.control.$valid; //I need to do something like this    
              }
        }
    }

I need to check in the isError function if the value in the control is valid or not

The template is:

<input class="input-field form-control" type="number" ng-model="model">

The HTML is:

 <form role="form" class="form-horizontal psi-keyrates-yieldform psi-keyrates-historical-topcurves" name="SampleControlsForm" novalidate>
      <px-number-input id="objectiveid" name="numericExample"    model="sampleDataModel.numericField" placeholder="Enter numeric value" label="Numeric" required maxlength="10"></px-number-input>
</form>

While the form variable tells me if the form (form.$valid) is valid or not, I need to know this particular directive has a valid value or not when the form is submitted. something like this form.control.$valid.

I do not know the name of the control in this directive as it will be set in the html.

I tried: var elem = ctrl.$name + '.' + element.attr('name') + '.$valid'; This returns the string "SampleControlsForm.numericExample.$valid" and if I add a watch on it, it doesn't help nor does scope.$eval.

I'm sure I'm not using it right.

2
  • 1
    You shouldn't have to define a template. Create a custom directive that requires ngModel, and add your own validation. Commented Apr 14, 2015 at 3:06
  • This is an existing directive that I need to modify. once the directive returns true or false, in the isError method, i need to add an image below it Commented Apr 14, 2015 at 3:18

1 Answer 1

1

Here is an example of a custom number validator that shows:

  1. How to require ngModel so you can access its controller.
  2. How to add your own custom validator by adding a property to $validators object (angular 1.3 and above). For angular < 1.3, use ngModelController.$setValidity
  3. How to setup a $watch on the $error object to insert/remove an image depending on whether the validation passes or fails.
  4. How to create a custom directive that works with ngModel without needing to define a template.

The $validators object allows you to register multiple validation directives for the same ngModel. To add a validator, simply add the validation directive to the same element as ngModel.

var app = angular.module('app', []);
app.directive('myNumber', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    compile: function(element, attr) {
      var img = angular.element('<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTTyptDmp09eMq1nHtcJHVTAMkKgqdi1ZiGMQSjFeYNApkO92zhCA" />');
           
      return function(scope, element, attr, ngModelCtrl) {
        function isNumber(n) {
            return !isNaN(parseFloat(n)) && isFinite(n);
        }
        
        ngModelCtrl.$validators.mynumber = function(val) {
          return isNumber(val);
        };
        scope.$watch(function() {
          return ngModelCtrl.$error.mynumber;
        }, 
        function(newVal) {
          if (newVal) {
            element.after(img);
          }
          else {
            img.remove();
          }
        });
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="app">
  <form name="form">
    <input type="text" name="age" my-number ng-model="age" /> {{ age }}
  </form>
  {{ form.age.$error }}
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

If anybody finds this in future, please look at docs.angularjs.org/api/ng/service/$compile#-compile- and the stuff just before link title: returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty. Which means instead of returning function from compile we can use the same piece of code with link attribute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.