AngularJS - Is it possible to change the value of ngModel attribute on directive in link or compile?

前端 未结 2 1095
鱼传尺愫
鱼传尺愫 2020-12-30 10:37

I am trying to create a directive that will add an ngModel attribute to a tag based on the attribute value. For example:

angular.module(\'myModule\').
  dir         


        
相关标签:
2条回答
  • 2020-12-30 11:10

    I was able to accomplish the goal by using a template function. I think it doesn't work in the link function because it occurs after all of the directives have been collected, so the compiler doesn't recognize that an ngModel directive has been added. I'm not sure why it doesn't work in the compile function, though (even if I set the priority to 100).

    Here's the working version of the directive:

    angular.module('myModule').
      directive('myDirective', function() {
        return {
          replace: true,
          template: function(elem, attr) {
            var newElem = '<input ng-model="model.' + attr.name + '">';
            return newElem;
          }
        };
      });
    
    0 讨论(0)
  • 2020-12-30 11:29

    You should check out the docs for the NgModelController. It will answer your question. For further explanation, here's the gist:

    You can capture a fourth argument to the link: function, which is your ng-model value. You use that object to read and set the model.

    link: function(scope, element, attrs, ngModel) {
        if(!ngModel) return; // do nothing if no ng-model
    
        // Specify how UI should be updated
        ngModel.$render = function() {
          element.html(ngModel.$viewValue || '');
        };
    
        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          scope.$apply(read);
        });
        read(); // initialize
    
        // Write data to the model
        function read() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if( attrs.stripBr && html == '<br>' ) {
            html = '';
          }
          ngModel.$setViewValue(html);
        }
    }
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题