2015-03-03 105 views
0

HTML”Angularjs:获得父元素宽度

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

+0

您可以通过注射'$ document'或'$ element'到您的控制器,但更好的方法访问DOM将是把DOM东西变成指令。如果你提供更多的信息,你想用父母的宽度来处理,我们可以给出更好的答案。 – hansmaad 2015-03-03 08:50:47

回答

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>

+0

检查答案,如果它已经解决了你的查询PLZ ... – 2015-03-03 09:48:31

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}); 
    } 
    } 
}]); 

在HTML

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

工作示例 here