Midhunsai Midhunsai - 4 months ago 14
AngularJS Question

How can I add css styles using directives?

I am trying to add some css styles dynamically using directives, I tried but some where I am missing.

This is my html code:

<tb-header-image image="{{BackgroundImage}}"></tb-header-image>


This is my directive and controller:

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {

$scope.BackgroundImage = "http://whatatimeline.com/covers/fb_profile_cover_13173327520f7.jpg";

});

app.directive('tbHeaderImage', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'backImage.html',
link: function (scope, elem, attr) {
console.log("coming to directive");

scope.backImage = attr.image;
console.log(scope.backImage);

elem.css({
width: '100%',
})

}
}
});


This is my backImage.html:

<div>
<img ng-src="{{backImage}}" alt="BackImage">
</div>


When I tried like above it is adding style to entire div like below image
enter image description here

But I want to add style like below image using directive
elem.css()


enter image description here

I am trying to add css style by
elem.css({})
, but it is appending to the div if image tag I want the style only for image tag and that too I have to style img tag from directive like when I write
elem.css()
then those styles have append for img tag only.

Thanks in advance.

Jai Jai
Answer

You have to use .find():

  elem.find('img').css({
    width: '100%',
  });

Because elem is the directive element. So, you have to find the children element of it.

Angular does uses the built-in jQuery methods and .find() has a limitation to lookup the elements by their tagnames only.