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.
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
Angular return a jQlite object. So, like jQuery
, to select current html element you need to use element[0]
.
Please refer this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With