Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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';
});
share|improve this answer
    
Thank you for your response. How do I get the width of the element in my controller though? That's where I really need it. I need to get the width in my controller. –  user70192 Oct 7 '14 at 13:14
    
You can pass in the element to the controller, just like the scope: function someControllerFunc($scope, $element){ } –  Mazzu Oct 7 '14 at 13:20
    
Please refer to code under "Updated Code" heading –  Mazzu Oct 7 '14 at 13:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.