1

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?

1 Answer 1

4

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';
});
Sign up to request clarification or add additional context in comments.

2 Comments

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.
You can pass in the element to the controller, just like the scope: function someControllerFunc($scope, $element){ }

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.