When do we know the actual width of an element in Angular?

前端 未结 4 1348
梦如初夏
梦如初夏 2021-01-31 17:22

I\'m tring to create a directive that will center a div.

So far, I have this code:

app.directive(\"setcenter\", function () {
    return {
        scope:         


        
4条回答
  •  轮回少年
    2021-01-31 18:02

    First, I only have used this logic when I defined a controller for a directive rather than a link function. So defining it in a link function instead may cause different behavior, but I suggest you try it there first and if you can't get it to work then switch to using a controller.

    As far as I can tell, the only change you would need to make this work would be to change $scope to scope calls and $element to element since the dependency injected objects become standard link function parameters.

      $scope.getElementDimensions = function () {
        return { 'h': $element.height(), 'w': $element.width() };
      };
    
      $scope.$watch($scope.getElementDimensions, function (newValue, oldValue) {
        //<>
      }, true);
    
      $element.bind('resize', function () {
        $scope.$apply();
      });
    

    The idea for this usage came to me after reading a very similar type of usage about watching the $window rather than the current element, the original work can be found here.

    Angular.js: set element height on page load

提交回复
热议问题