Angularjs:获取父元素宽度

时间:2015-03-03 08:47:23

标签: angularjs

HTML"

<div id="parent">
      <input type=button ng-click="getWidth()">
</div>

JS:

 function Ctrl($scope) {
        $scope.getWidth = function(){
           // How to get div[id=parent] width here?
        } 

    }

所以我的问题是如何在getWidth方法中获取父div?

2 个答案:

答案 0 :(得分:1)

像hansmaad的回答一样,你最好使用指令来处理DOM的东西。

app.directive('getWidth', ['$timeout', '$location', function($timeout, $location) {
  return {
    scope: {
      callbackFn: "&"
    },
    link: function(scope, elem, attrs) {
      scope.callbackFn({width: elem[0].clientWidth});
    }
  }
}]);

in html

<body ng-controller="MainCtrl" >
    <div get-width callback-fn="returnWidth(width)" style="height:100%; width: 100%;">
          <p >Hello {{name}}!</p>
    </div>
  </body>

工作示例 here

答案 1 :(得分:0)

使用$event.target获取元素单击,然后使用jquery查找宽度

function SimpleController($scope) {
  $scope.width = 0;
  $scope.getWidth = function($event) {
    // How to get div[id=parent] width here?
    $scope.width = $($event.target).parent().outerWidth();

  }
}
#parent{
  background-color : red;
  width : 200px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div class="container" ng-app="" ng-controller="SimpleController">


  <div id="parent">
    parent width : {{width}}
    <button type=button ng-click="getWidth($event)"> find width </button>
  </div>

</div>