programing

Angular에서 요소의 실제 너비는 언제 알 수 있습니까?

javajsp 2023. 3. 15. 19:19

Angular에서 요소의 실제 너비는 언제 알 수 있습니까?

나는 div를 중심에 둘 디렉티브를 만들기 위해 노력하고 있다.

지금까지의 코드는 다음과 같습니다.

app.directive("setcenter", function () {
    return {
        scope:{
            setcenter: '='
        },
        link: function (scope, element, attrs) {

            scope.$watch('setcenter', function (newValue) {
                if (newValue == true) {
                    var width = element.width();
                    element.css('position', 'absolute');
                    element.css('top', '80px');
                    element.css('left', '50%');
                    element.css('z-index', '200');
                    element.css('margin-left', '-' + width / 2 + 'px');
                }
            });
        }
    }
});

문제는 요소의 폭입니다.이 지시문의 요점은 이 지시문을 사용하는 div에는 너비가 설정되어 있지 않다는 것입니다.나는 이 지시문이 폭을 계산하고 div의 중심을 맞추길 원한다.

내가 마주치는 문제는 디렉티브가 호출되었을 때 div의 실제 폭을 아직 알 수 없다는 것이다.제 상황에서 이것을 사용하면 div는 800px이지만, 페이지 로딩이 끝나면 div는 221px가 됩니다.

그럼 어떻게 하면 div의 실제 폭을 알 수 있을까요?

첫째, 링크 함수가 아닌 디렉티브컨트롤러를 정의할 때만 이 논리를 사용했습니다.따라서 링크 함수로 정의하면 다른 동작이 발생할 수 있습니다.단, 먼저 링크 함수에서 실행해 보고, 동작하지 않으면 컨트롤러를 사용하는 것으로 전환하는 것이 좋습니다.

제가 알기로는, 이 작업에 필요한 유일한 변경은 $scope를 scope calls로 변경하고 $element를 element로 변경하는 것입니다.이는 종속성이 삽입된 객체가 표준 링크 함수 파라미터가 되기 때문입니다.

  $scope.getElementDimensions = function () {
    return { 'h': $element.height(), 'w': $element.width() };
  };

  $scope.$watch($scope.getElementDimensions, function (newValue, oldValue) {
    //<<perform your logic here using newValue.w and set your variables on the scope>>
  }, true);

  $element.bind('resize', function () {
    $scope.$apply();
  });

이 사용법에 대한 아이디어는 현재 요소가 아닌 $window를 보는 것과 매우 유사한 사용법을 읽고 떠올랐습니다.원작은 여기에서 찾을 수 있습니다.

Angular.js: 페이지 로드 시 요소 높이 설정

제임스의 답변은 나를 다음과 같이 이끌었다.

app.directive('measureInto', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(function() {
                    return element[0].clientWidth;
                }, function(value){
                    scope[attrs.measureInto] = element[0].clientWidth + 10;
                });
            }
        };
    });

실행 시 이 값을 추가하여 원하는 요소의 너비를 원하는 범위 변수에 할당합니다.

페이지상의 모든 ng-ifs(또는 ngAnimate를 사용하는 다른 것)가 해결되었을 때, 같은 문제가 발생했을 가능성이 있기 때문에, 치수는 확실히 올바른 것을 알 수 있었습니다.이 경우 새로운 청취자를 추가하지 않아도 됩니다.

$scope.tryGetElementDimensions = function () {
    if (!angular.element("your-element") || ((angular.element("your-element")[0].classList).contains("ng-animate")
       $timeout(function() {
           $scope.tryGetElementDimensions()
       })
    }
    else {
        $scope.getElementDimensions()
    } 

$scope.getElementDimensions = function (){
    //whatever you actually wanted to do
}

link: function (scope, element, attrs) {
    $scope.tryGetElementDimensions()
}

Angular는 애니메이션이 진행되는 동안 ng-animate 및 ng-enter, ng-leave 클래스를 추가합니다.이러한 클래스가 모두 삭제되면 종료된 것이 확실합니다.두 번째 인수 없이 $120은 다음 다이제스트를 기다립니다.

아직 코멘트를 드릴 수 없습니다. 따라서 이 답변입니다.strom2357이 제안하는 것과 유사한 솔루션을 찾았습니다.돔이 언제 준비되었는지 알려드리기 위해 $190이 매우 효과적이며 매우 간단합니다.이 솔루션을 사용하여 ui-view 요소의 폭을 얻고 있습니다.순식간에 찾았어.

var app = angular.module('app', []);

app.controller('MyController', function($timeout, $scope){

  $timeout(function(){
    //This is where you would get width or height of an element
    alert('DOM ready');
  });

  alert('DOM not ready');

});

언급URL : https://stackoverflow.com/questions/17726313/when-do-we-know-the-actual-width-of-an-element-in-angular