Reputation: 14204
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
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:
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