What is the link: "parameters" (scope, element, attrs)? Angularjs

So, I've been using AngularJS for a couple of months now, and I browsed the Internet and my book, AngularJS Directives, to answer this question.

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

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

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

Thanks!

+5
source share
2 answers

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

scope : this is the scope of your user directive, similar to $scope in the controller

element : this is an element of your user directive

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

For example, if you create a custom directive called myDirective , and you are likely to use it in your html particles as follows:

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

Here 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'); }); } 

In addition, in the above communication function, you can bind an 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, which is the controller of another directive that is required in your custom directive. eg:.

 require: '^ngModel' .... function link(scope, element, attrs, ngModelCtrl) { .... } 
+5
source

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

element : this is an element of your custom directive

attrs : there is nothing but a parameter

-1
source

Source: https://habr.com/ru/post/1238391/


All Articles