0

I have a directive defined as:

module.directive('inputChanged', function () {
        function link(scope, element, attrs) {
            var field = attrs.ngModel;
            if (field) {
                var fn = "model.changed('" + field + "')";
                element.attr('ng-change', fn);
            }            
        }

        return {
            restrict: 'A',
            link: link
        }
    });

which I am using like:

<input ng-model="model.user.middleName" input-changed type="text" class="k-textbox">

The goal is to dynamically inject the ng-change with the model field as parameter. My scenario is actually a bit more complex, but I am simplifying it for this question. This is why I need to inject it dynamically and not place it directly in the input markup.

This works and I can see the ng-change in the markup once the page is rendered.

<input ng-model="model.user.middleName.value" type="text" class="k-textbox ng-valid ng-not-empty ng-dirty ng-valid-parse ng-touched" ng-change="model.changed('model.user.middleName.value')" aria-invalid="false">

The problem is that model.changed(...) is not firing. If I hardcode it instead of using the directive, everything works as expected.

What am I missing?

Thank you.

1 Answer 1

1

You need to compile the element after adding the ng-change directive.

angular
  .module('app')
  .directive('inputChanged', inputChanged);

  function inputChanged($compile) {

  var directive = {
      restrict: 'A',
      link: link,
      terminal: true,
      priority: 1000,
  };
  return directive;

  function link(scope, element, attrs) {
    var field = attrs.ngModel;
    if (field) {
      var fn = "main.changed(" + field + ")";

      // Remove the attribute to prevent  
      // an infinite compile loop
      element.removeAttr('input-changed');
      element.attr('ng-change', fn);
      $compile(element)(scope);
    }
  }
};

Working plunker.

More information about adding directives from a directive in this post.

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

1 Comment

awesome @ndoes. that did it. thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.