Cétia Cétia - 7 months ago 9
Javascript Question

What's the use of the "attrs" parameter in an angular directive link function

Considering this directive :

.directive('myDirective', function(httpRequestTracker) {
return {
restrict: 'EA',
scope: {
myvar: "=",
},
link: function($scope, elem, attrs) {
console.log($scope.myvar, attrs.myvar);
}
};
})


and this JS console output :


> undefined undefined // if no attribute

> value value // if attribute value = "value"


What is the use of the
attr
parameter of the
link
function ? What is the difference with $scope ?

Thanks

Answer

attrs is just a raw list of attributes on a directive
scope is more sophisticated, you can use three different operators to populate it with values:

  • = evaluates expression in HTML, and may contain objects
  • @ interprets value passed as string. always.
  • & gives you access to functions defined on parent scope
Comments