Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the link: Function "parameters" (scope, element, attrs)? AngularJS

So I've been using AngularJS for a couple months now and I've scoured the internet and my AngularJS Directives book for an answer to this.

In directives, I almost always see this block of code:

link: function(scope, element, attrs) { 
    //body
}

What exactly are the items inside the function "scope, element, attrs"? This might be a stupid question but I cannot seem to find the answer anywhere.

Thanks!

like image 225
LargeCrimsonFish Avatar asked Dec 16 '15 15:12

LargeCrimsonFish


1 Answers

the parameters scope, element, and attrs are defined for your custom directive, as per the documentation here, but you can rename them to your like.

scope: this is the scope for your custom directive, similar to the $scope in a controller

element: this is the element of your custom directive

attrs: this is the set of attributes in your custom directive. (should be the attributes of the element, thanks to @zeroflagL for correction!)

For example, if you build a custom directive named myDirective, and you would probably use it in your html partials like this:

<my-directive num-rows="3"></my-directive>

Here, the num-rows is an attribute for your directive, and you can get its value in your link function:

function link(scope, element, attrs) {
    console.log('num-rows:', attrs.numRows);
    //you can change its value, too
    attrs.$set('numRows', '10'); //attrs setter

    //you can watch for its changes to trigger some event
    attrs.$observe('numRows', function(newVal) {
       console.log('trigger some event for the changes in numRows here');
    });
}

Also, in the link function above, you can bind the element/directive to an action:

element.bind('click', function() {
   console.log('do something with the click event');
});

I suggest you spend some time reading the documentation. The link function can take a 4th parameter that is the controller of another directive that you require in your custom directive. e.g.:

require: '^ngModel'
....

function link(scope, element, attrs, ngModelCtrl) {
  ....
}
like image 153
TonyGW Avatar answered Oct 21 '22 11:10

TonyGW