在AngularJS中获取运行时HTML元素的宽度

时间:2014-10-07 12:06:53

标签: javascript angularjs

我正在通过在AngularJS中构建指令慢慢摸索。目前,我的指令如下:

.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"
      };
    }
  };
});

my-directive.html中的标记如下所示:

<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>

当用户开始输入时,将在控制器中触发getLocation函数。触发getLocation时,我需要获取字段文本框的宽度。如何在AngularJS中获取该元素的宽度?

1 个答案:

答案 0 :(得分:4)

您需要在链接函数中传递element作为参数,并使用offsetWidth计算其宽度。

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

}

您可以在以下链接中以某种方式引用类似的方案:

  1. https://gist.github.com/Zmaster/6923413
  2. http://plnkr.co/edit/DeoY73EcPEQMht66FbaB?p=preview
  3. 希望这会帮助你:))

    更新代码:

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