簡體   English   中英

在運行時在AngularJS中獲取HTML元素的寬度

[英]Get Width of HTML element at runtime in 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中獲取該元素的寬度?

您需要在鏈接函數中將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

希望這會幫到你:)

更新的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM