Search code examples
angularjsangular-directive

Add ng-required attribute dynamically in directive


Currently I have defined my custom directive:

.directive('foo', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attributes, ngModel) {

      scope.isRequired = function () {
        return !attributes.disabled; // more complicated test
      };

    }
  };
}])

And it's used like:

<input name="a" type="text" foo ng-required="isRequired" />
<input name="b" type="text" foo ng-required="isRequired" />
<input name="c" type="text" foo ng-required="isRequired" />

Is it possible to define ng-required attribute in the directive instead of linking the isRequired method in the template ?

Expected result:

link: function (scope, element, attributes, ngModel) {

  element.attr('ng-required', function () {
    return !attributes.disabled; // more complicated test
  });

}

However this function is not called, ng-required is not applied.


Solution

  • Supposed you have an input which should be extended, you can do something like this:

    <input ng-model="bar" foo /> 
    

    and your directive:

    .directive('foo', [function () {
        return {
           restrict: 'A',
           scope: {},
           template: '<input ng-required="isRequired" />',
           controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs){
              $scope.isRequired = function(){
                  return !attributes.disabled; // more complicated test
              }
            }]
         };
     }]);
    

    You can also bind additional attributes to your internal scope:

    <input ng-model="bar" foo foo-required="somefunction" />
    

    and in your directive:

    scope: {
       requiredCallback: &fooRequired
    }