2014-10-07 74 views
1

我慢慢地通過在AngularJS中構建指令來摸索我的方式。目前,我的指令看起來像這樣:在AngularJS的運行時獲取HTML元素的寬度

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

的標記在我-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中該元素的寬度?

回答

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

希望這將幫助你:)

更新的代碼:

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

感謝您的回覆。我如何獲得控制器中元素的寬度?那就是我真正需要的地方。我需要在我的控制器中獲得寬度。 – user70192 2014-10-07 13:14:07

+0

您可以將元素傳遞到控制器,就像範圍: 函數someControllerFunc($ scope,$ element){ } – Mazzu 2014-10-07 13:20:59

+0

請參閱「更新代碼」標題下的代碼 – Mazzu 2014-10-07 13:26:55