3

I have an angularjs component, which has a template, a controller, some bindings, some transcluded parts.

I place this component in my DOM, together with its attributes:

<mycomponent attr1="x" attr2="y"></mycomponent>

These attributes values will be used by component's controller and/or in the component's template to be transcluded somewhere.

I need to run a function after the component has been completely created, i.e. it's template has been created on the DOM and all the transcluded elements have been given a value.

How can I accomplish that? I tried placing the function in the $postLink() hook of the controller, however when $postLink() fires I see that the transclusion has not run yet.

Moreover, I don't like to have to mess with component's controller, since the component is very general, I place it on several places in the DOM, and only ONE of them should run this function after its complete creation.

edoedoedo
  • 1,469
  • 2
  • 21
  • 32

3 Answers3

1

For AngularJS 1 application, there are two ways of running a function after DOM initialization :

  1. You can use $timeout without a delay - $timeout(function() { /* Invoke your function */ });
  2. Or Use .ready() which is provided by Angular's jqLite
ManishSingh
  • 1,804
  • 1
  • 12
  • 11
  • 1
    I found this to be the case for AngularJS 1. There is no lifecycle method or hook to use. $onInit does not guarantee that the component's view and child views are finished loading on the UI, and $viewContentLoaded is not used on a component. – angtlin Sep 26 '18 at 18:56
1

From "Components have a well-defined lifecycle" paragraph in AngularJS docs:

$postLink() - Called after this controller's element and its children have been linked. Similar to the post-link function this hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain templateUrl directives will not have been compiled and linked since they are waiting for their template to load asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather different in Angular 1 there is no direct mapping and care should be taken when upgrading.

JohnDoenym
  • 55
  • 1
  • 7
0

In Angular 2:

ngAfterViewInit()

Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked(). A component-only hook.

in Jquery:

$( document ).ready(function() {
        console.log( "document loaded" );
    });

in javascript:

window.onload(function(){
//here
});

in angular1:

angular.element(document).ready(function () {
        //content here
    });
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
  • Question ask for AngularJS, the v1, and as far as i know from v1.5 there is the $onInit lifecycle hook method. – ZR87 Sep 03 '22 at 16:22