0

I have a textarea that I want to resize on certain events using Angular directives.

What I have so far works for the event 'keydown' but I can't seem to figure out how to get the functionality working for other events.

I also tried figuring out how I could possibly achieve this functionality without using jquery's events.

What I would like is to trigger the update function once the data has been loaded into the textarea and when the entire browser window is resized.

Directive:

var app = angular.module('directives', []);

app.directive('autoGrow', function() {
  return function(scope, element, attr){
    var update = function(event) {
      element.css('height', element[0].scrollHeight + 'px');
    }
    element.bind('keydown', update); // Works
    element.bind('load', update);    // Doesn't quite have desired effect.
    element.bind('resize', update);  // Doesn't quite have desired effect.
    update();
  }
});

HTML:

<textarea auto-grow type="text" ng-model="model.foo">

Edit: Just to make sure I got my point across, all the bind elements above trigger as they are supposed to. I am just looking for a way that I can trigger my update function when: window is resized and when the ng-model changes or data is updated in the element.

2

1 Answer 1

1

Here is my proposal:

  1. inject the $window service to be able to register a callback to the resize event
  2. specify that you custom directive requires ng-model directive to be able to watch for modelchanges

    var app = angular.module('directives', []);

    app.directive('autoGrow', function($window) { return { require: 'ngModel', link: function(scope, element, attr, ngModelCtrl){

        scope.$watch(function () {
          return ngModelCtrl.$modelValue;
           },
           update,
           true // if deepwatch is required
           );
    
        var update = function(event) {
          element.css('height', element[0].scrollHeight + 'px');
        }
    
        element.on('keydown', update); // Works
        element.on('load', update);    // Doesn't quite have desired effect.
        element.on('resize', update);  // Doesn't quite have desired effect.
        update();
    
        angular.element($window).on('resize', update);
      }
    

    };
    });

More resources:

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

Comments

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.