user70192
user70192

Reputation: 14204

Get Width of HTML element at runtime in AngularJS

I'm slowly fumbling my way through building a directive in AngularJS. Currently, my directive looks like this:

.directive('myDirective', function () {
  return {
    restrict:'E',
    transclude: true,
    scope: {
      showLinks: '=?',
      query: '='
    },
    templateUrl: '/directives/my-directive.html',
    controller: function ($scope) {
      if (angular.isUndefined($scope.showLinks)) {
        $scope.showLinks = true;
      }

      $scope.getLocation = function(l) {
        // Get width of "field"
      };
    }
  };
});

The markup in my-directive.html looks like this:

<div style="width:100%;">
    <input id="field" type="text" autofocus autocomplete="off" class="form-control" ng-model="query"
           typeahead="option as option.Name for option in getLocation($viewValue)"
           typeahead-min-length="3" typeahead-template-url="location.html" />
    <script type="text/ng-template" id="location.html">
      {{showLinks}} <!-- Never renders -->
      <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span>
    </script>
</div>

When a user starts typing, the getLocation function is fired in the controller. I need to get the width of the field textbox when getLocation is fired. How do I get the width of that element in AngularJS?

Upvotes: 1

Views: 9278

Answers (1)

Mazzu
Mazzu

Reputation: 2839

You need to pass element as parameter in link function and calculate its width using offsetWidth.

link: function(scope, element, attrs) {
        var elInput = element.find('input');
        alert(elInput[0].offsetWidth) ; // gives offsetwidth of element

}

You can refer to somehow similar scenarios at below links:

  1. https://gist.github.com/Zmaster/6923413
  2. http://plnkr.co/edit/DeoY73EcPEQMht66FbaB?p=preview

Hope this will help you out :)

Updated Code:

app.controller('MainCtrl', function($scope, $element) {
  var elInput = $element.find('input');
  alert(elInput[0].offsetWidth);
  $scope.name = 'World';
});

Upvotes: 4

Related Questions