0

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

    }

So my question is how to get parent div in getWidth method?

1
  • You could access the dom by injecting $document or $element into your controller but better practice would be to put DOM stuff into directives. We could give a better answer if you provide more information would you want to do with parent's width. Commented Mar 3, 2015 at 8:50

2 Answers 2

1

like hansmaad's answer, you better use directive for handling DOM stuffs.

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>

working example here

Sign up to request clarification or add additional context in comments.

Comments

0

use $event.target to get the element click and then use jquery to find width

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.