Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of $postLink() in components

Tags:

angularjs

I can't find any example of $postLink() from AngularJS components, part Components have a well-defined lifecycle. Can you please provide a simple example just of the method implented in a controller where I could realize how to manipulate DOM?

The only article explaining $postLink() a little is http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html .

It seems like that there is no argument in $postLink(). Thus I would inject $element and modify the DOM.

like image 329
Amio.io Avatar asked May 02 '16 13:05

Amio.io


People also ask

What is postLink in angular?

Use this hook for releasing external resources, watches and event handlers. $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.

What is Oninit in AngularJS?

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.


1 Answers

So the usage is simple:

function Controller($element) {
        var self = this;

        self.$postLink = $postLink;

        function $postLink() {
            $element.attr("mymymy", "xxxxxx");
        }
}

Then let's say my component name is myComponent and using an inspector of a browser you could see a modified tag with an added attribute from above: <my-component mymymy="xxxxxx"></my-component>.

like image 94
Amio.io Avatar answered Sep 19 '22 08:09

Amio.io