돔 렌더링이 완료된 후 디렉티브를 실행하려면 어떻게 해야 합니까?
(Angular JS 문서를 읽음으로써) 명백한 솔루션이 없는 것처럼 보이는 간단한 문제가 있습니다.
Angular JS 디렉티브는 다른 DOM 요소의 높이를 기반으로 계산하여 DOM 내의 컨테이너 높이를 정의합니다.
지시문 내부에서는 다음과 같은 일이 일어나고 있습니다.
return function(scope, element, attrs) {
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
}
문제는 디렉티브가 실행될 때$('site-header')찾을 수 없습니다. 필요한 jQuery 랩된 DOM 요소 대신 빈 배열을 반환합니다.
디렉티브 내에서 DOM이 로드된 후에만 실행할 수 있는 콜백이 있습니까?또, 통상의 jQuery selector 스타일의 쿼리를 개입시켜 다른 DOM 요소에 액세스 할 수 있습니까?
$('site-header')가 어떻게 구성되느냐에 따라 달라집니다.
지연 0으로 $timeout을 사용할 수 있습니다.예를 들어 다음과 같습니다.
return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}
주사 놓는 거 잊지 마$timeout지시사항:
.directive('sticky', function($timeout)
방법은 다음과 같습니다.
app.directive('example', function() {
return function(scope, element, attrs) {
angular.element(document).ready(function() {
//MANIPULATE THE DOM
});
};
});
아마 작가는 더 이상 내 대답을 필요로 하지 않을 것이다.그러나 완성도를 높이기 위해 다른 사용자가 유용하게 사용할 수 있다고 생각합니다.가장 간단하고 최선의 해결책은$(window).load()반환된 함수의 본체 내부에 있습니다.(또는document.ready모든 이미지가 필요한지 아닌지에 따라 달라집니다.)
사용.$timeout저의 겸손한 의견으로는 매우 약한 선택이며 경우에 따라서는 실패할 수도 있습니다.
사용하는 완전한 코드는 다음과 같습니다.
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function($scope, $elem, attrs){
$(window).load(function() {
//...JS here...
});
}
}
});
이 있다ngcontentloaded이벤트도 쓸 수 있을 것 같아요.
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
$$window = $ $window
init = function(){
contentHeight = elem.outerHeight()
//do the things
}
$$window.on('ngcontentloaded',init)
}
}
});
외부 리소스로 인해 $timeout을 사용할 수 없고 특정 타이밍 문제로 인해 디렉티브를 사용할 수 없는 경우 broadcast를 사용하십시오.
더하다$scope.$broadcast("variable_name_here");필요한 외부 리소스 또는 장시간 실행되는 컨트롤러/컨트롤러/컨트롤러 완료 후
그런 다음 외부 리소스가 로드된 후 다음을 추가합니다.
$scope.$on("variable_name_here", function(){
// DOM manipulation here
jQuery('selector').height();
}
예를 들어 지연된 HTTP 요청의 약속입니다.
MyHttpService.then(function(data){
$scope.MyHttpReturnedImage = data.image;
$scope.$broadcast("imageLoaded");
});
$scope.$on("imageLoaded", function(){
jQuery('img').height(80).width(80);
}
저도 비슷한 문제가 있어서 여기서 제 해결책을 공유하려고 합니다.
다음 HTML을 사용하고 있습니다.
<div data-my-directive>
<div id='sub' ng-include='includedFile.htm'></div>
</div>
문제:부모 div의 디렉티브 링크 기능에서 자녀 div #sub를 조회하고 싶었습니다.그러나 디렉티브의 링크 기능이 실행되었을 때 ng-include가 완료되지 않았기 때문에 빈 오브젝트를 제공했을 뿐입니다.그래서 처음에 $timeout을 사용하여 문제를 해결했습니다.이것은 효과가 있었지만 지연 파라미터는 클라이언트 속도에 의존합니다(아무도 좋아하지 않습니다).
작동하지만 더러움:
app.directive('myDirective', [function () {
var directive = {};
directive.link = function (scope, element, attrs) {
$timeout(function() {
//very dirty cause of client-depending varying delay time
$('#sub').css(/*whatever*/);
}, 350);
};
return directive;
}]);
다음은 클린솔루션입니다.
app.directive('myDirective', [function () {
var directive = {};
directive.link = function (scope, element, attrs) {
scope.$on('$includeContentLoaded', function() {
//just happens in the moment when ng-included finished
$('#sub').css(/*whatever*/);
};
};
return directive;
}]);
그게 도움이 될지도 몰라
언급URL : https://stackoverflow.com/questions/12240639/how-can-i-run-a-directive-after-the-dom-has-finished-rendering
'programing' 카테고리의 다른 글
| 배열에 존재하는 값을 기반으로 한ng-show (0) | 2023.03.03 |
|---|---|
| MongoDb에 대한 현재 연결 수를 확인합니다. (0) | 2023.02.26 |
| Angular에서의 지시 장치 테스트에서 서비스를 주입하는 방법JS (0) | 2023.02.26 |
| 스프링 MVC와 스프링부츠의 차이점 (0) | 2023.02.26 |
| DB2와 Oracle 관점에서 CLOB와 BLOB의 차이점은 무엇입니까? (0) | 2023.02.26 |