Midhunsai Midhunsai - 3 months ago 6
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;

width: '100%',


This is my backImage.html:

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

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

enter image description here

I am trying to add css style by
, 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
then those styles have append for img tag only.

Thanks in advance.

Jai Jai

You have to use .find():

    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.