Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directives and the link function

Could someone explain why when I try to change the background colour of my custom directive to red using this piece of code it doesn't work.

app.directive('isolateDir', [function(){

    return {
        restrict: 'E',
        templateUrl: 'template.html',
        scope: { stockData: "="},
        link: function(scope, element, attr){
            scope.changeColour = function(){
                element[0].style.backgroundColor = 'red';
            };
        }
    }
}]);

And yet when I use this piece it does.

app.directive('isolateDir', [function(){

    return {
        restrict: 'E',
        templateUrl: 'template.html',
        scope: { stockData: "="},
        link: function(scope, element, attr){
            scope.changeColour = function(){
                element.style.backgroundColor = 'red';
            };
        }
    }
}]);

I thought the element parameter in the link function referenced that instance of the directive.

like image 418
2K01B5 Avatar asked Sep 18 '25 20:09

2K01B5


2 Answers

Because element is the jqLite-wrapped element that this directive matches. The DOM element it self is the element[0].

You can find more information here:

https://docs.angularjs.org/guide/directive

Take a look at this plunker that output in console the wrapped element and the DOM element:

http://plnkr.co/edit/Kcu7nHVzacbsSDiXSt6U?p=preview

like image 101
Diego Unanue Avatar answered Sep 21 '25 08:09

Diego Unanue


Angular return a jQlite object. So, like jQuery, to select current html element you need to use element[0].

Please refer this article.

like image 44
Varun Avatar answered Sep 21 '25 09:09

Varun