it-source

콘텐츠 로드 후 호출할 AngularJs 이벤트

criticalcode 2023. 2. 8. 17:59
반응형

콘텐츠 로드 후 호출할 AngularJs 이벤트

페이지 내용이 로드되면 호출하고 싶은 기능이 있습니다.$view Content Loaded에 대한 내용을 읽었는데 잘 되지 않습니다.저는 이런 걸 찾고 있습니다.

document.addEventListener('DOMContentLoaded', function () { 
     //Content goes here 
}, false);

위의 통화는 AngularJs 컨트롤러에서는 사용할 수 없습니다.

$viewContentLoaded 문서에 따르면 동작할 것으로 예상됩니다.

ngView콘텐츠가 새로고침될 때마다 출력됩니다.

$viewContentLoaded이 이벤트를 수신하려면 다음과 같은 부모 컨트롤러가 필요합니다.

<div ng-controller="MainCtrl">
  <div ng-view></div>
</div>

부터MainCtrl이벤트를 들을 수 있습니다.

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

데모 확인

각도 1.6.X 미만

angular.element(document).ready(function () {
    console.log('page loading completed');
});

각도 > = 1.6.x

angular.element(function () {
    console.log('page loading completed');
});

고정 - 2015.06.09

지시어 및 각도 요소 사용ready다음과 같은 방법:

js

.directive( 'elemReady', function( $parse ) {
   return {
       restrict: 'A',
       link: function( $scope, elem, attrs ) {    
          elem.ready(function(){
            $scope.$apply(function(){
                var func = $parse(attrs.elemReady);
                func($scope);
            })
          })
       }
    }
})

html

<div elem-ready="someMethod()"></div>

또는 controller-as 구문을 사용하는 사용자의 경우...

<div elem-ready="vm.someMethod()"></div>

이 방법의 장점은 UI를 원하는 만큼 폭넓게 사용할 수 있고 컨트롤러에서 DOM 로직을 제거할 수 있다는 것입니다.나는 이것이 권장되는 Angular 방식이라고 주장한다.

같은 노드상에서 동작하는 다른 디렉티브가 있는 경우는, 이 디렉티브의 우선순위를 설정할 필요가 있습니다.

를 추가하여 직접 호출할 수 있습니다.{{YourFunction()}}HTML 요소 뒤에 있습니다.

다음은 입니다.

저는 구글 차트를 다룰 때 이 논리를 구현해야 했습니다.html inside 컨트롤러 정의 끝에 추가했습니다.

  <body>
         -- some html here -- 
--and at the end or where ever you want --
          <div ng-init="FunCall()"></div>
    </body>

그리고 그 함수는 단순히 논리적으로 불러내라.

$scope.FunCall = function () {
        alert("Called");
}
var myM = angular.module('data-module');

myM.directive('myDirect',['$document', function( $document ){

    function link( scope , element , attrs ){

        element.ready( function(){

        } );

        scope.$on( '$viewContentLoaded' , function(){

            console.log(" ===> Called on View Load ") ;

        } );

    }

    return {
        link: link
    };

}] );

위의 방법이 나에게 효과가 있었다.

onload 이벤트의 javascript 버전을 angular js로 호출할 수 있습니다.이 ng-load 이벤트는 div, span, body, iframe, img 등의 돔 요소에 적용할 수 있습니다.이 링크는 기존 프로젝트에 ng-load를 추가하는 링크입니다.

각도 js에 대한 ng-load 다운로드

iframe이 로드되면 testCallback의 예를 다음에 나타냅니다.컨트롤러에서 함수가 호출됩니다.

JS

    // include the `ngLoad` module
    var app = angular.module('myApp', ['ngLoad']);
    app.controller('myCtrl', function($scope) {
        $scope.testCallbackFunction = function() {
          //TODO : Things to do once Element is loaded
        };

    });  

HTML

  <div ng-app='myApp' ng-controller='myCtrl'> 
      <iframe src="test.html" ng-load callback="testCallbackFunction()">  
  </div>

$digest are in progress 오류가 발생할 경우 다음과 같이 도움이 될 수 있습니다.

return {
        restrict: 'A',
        link: function( $scope, elem, attrs ) {
            elem.ready(function(){

                if(!$scope.$$phase) {
                    $scope.$apply(function(){
                        var func = $parse(attrs.elemReady);
                        func($scope);
                    })
                }
                else {

                    var func = $parse(attrs.elemReady);
                    func($scope);
                }

            })
        }
    }

사용하고 있었습니다.{{myFunction()}}템플릿에 추가되었지만 여기서 다른 방법을 찾았습니다.$timeout컨트롤러 내부에 있습니다.공유하려고 했는데, 나한테는 잘 먹혔어.

angular.module('myApp').controller('myCtrl', ['$timeout',
function($timeout) {
var self = this;

self.controllerFunction = function () { alert('controller function');}

$timeout(function () {
    var vanillaFunction = function () { alert('vanilla function'); }();
    self.controllerFunction();
});

}]);

페이지 로드 후 실행은 이벤트 수신기를 창 로드 이벤트로 설정하여 부분적으로 충족시켜야 합니다.

window.addEventListener("load",function()...)

내부module.run(function()...)angular의 경우 모듈 구조와 종속성에 모두 액세스할 수 있습니다.

하면 돼요.broadcast ★★★★★★★★★★★★★★★★★」emit이치노

예를 들어 다음과 같습니다.

  • 모듈 설정 온로드 이벤트 및 빌드 로직
  • 모듈 브로드캐스트이벤트를 로직이 필요할 때 컨트롤러로 전송
  • 컨트롤러는 모듈 부하 프로세스를 기반으로 자체 로직을 수신하고 실행합니다.

특정 요소를 완전히 로드하려면 해당 요소에 ng-init를 사용합니다.

★★<div class="modal fade" id="modalFacultyInfo" role="dialog" ng-init="initModalFacultyInfo()"> ..</div>

initModalFacultyInfo() 함수는 컨트롤러 내에 존재해야 합니다.

중첩된 뷰가 있는 경우 - $viewContentLoaded는 중첩된 뷰마다 트리거됩니다.최종 $viewContentLoaded를 찾기 위해 이 회피책을 만들었습니다.Prerender가 요구하는 $window.preenderReady 설정에는 문제가 없는 것 같습니다(메인 app.js에서 .run()으로 이동합니다).

// Trigger $window.prerenderReady once page is stable
// Note that since we have nested views - $viewContentLoaded is fired multiple
// times and we need to go around this problem
var viewContentLoads = 0;
var checkReady = function(previousContentLoads) {
  var currentContentLoads = Number(viewContentLoads) + 0; // Create a local copy of the number of loads
  if (previousContentLoads === currentContentLoads) { // Check if we are in a steady state
    $window.prerenderReady = true; // Raise the flag saying we are ready
  } else {
    if ($window.prerenderReady || currentContentLoads > 20) return; // Runaway check
    $timeout(function() {checkReady(currentContentLoads);}, 100); // Wait 100ms and recheck
  }
};
$rootScope.$on('$stateChangeSuccess', function() {
  checkReady(-1); // Changed the state - ready to listen for end of render
});
$rootScope.$on('$viewContentLoaded', function() {
  viewContentLoads ++;
});
var myTestApp = angular.module("myTestApp", []); 
myTestApp.controller("myTestController", function($scope, $window) {
$window.onload = function() {
 alert("is called on page load.");
};
});

나에게 효과가 있는 솔루션은 다음과 같다.

app.directive('onFinishRender', ['$timeout', '$parse', function ($timeout, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                    if (!!attr.onFinishRender) {
                        $parse(attr.onFinishRender)(scope);
                    }
                });
            }

            if (!!attr.onStartRender) {
                if (scope.$first === true) {
                    $timeout(function () {
                        scope.$emit('ngRepeatStarted');
                        if (!!attr.onStartRender) {
                            $parse(attr.onStartRender)(scope);
                        }
                    });
                }
            }
        }
    }
}]);

컨트롤러 코드는 다음과 같습니다.

$scope.crearTooltip = function () {
     $('[data-toggle="popover"]').popover();
}

HTML 코드는 다음과 같습니다.

<tr ng-repeat="item in $data" on-finish-render="crearTooltip()">

용 i i i i를 쓴다.setInterval로딩된 콘텐츠를 기다립니다.이것이 당신이 그 문제를 해결하는 데 도움이 되기를 바랍니다.

var $audio = $('#audio');
var src = $audio.attr('src');
var a;
a = window.setInterval(function(){
    src = $audio.attr('src');
    if(src != undefined){
        window.clearInterval(a);
        $('audio').mediaelementplayer({
            audioWidth: '100%'
        });
    }
}, 0);

언급URL : https://stackoverflow.com/questions/21715256/angularjs-event-to-call-after-content-is-loaded

반응형