0

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

This is my html code:

<header-image image="{{BackgroundImage}}"></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('headerImage', 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.

2

4 Answers 4

2

Else you can do css like that :

<body ng-app="myApp" ng-controller="myCtrl">

<h1 ng-style="myObj">Welcome</h1>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
    "color" : "white",
    "background-color" : "coral",
    "font-size" : "60px",
    "padding" : "50px"
}
});
</script>
</body>

Hope help you.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

if iam using "img" tag ,"h1" and "h2" in the same directive then how can i write styles using diretive like same as above @jai
0

You can do:

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

Or just create a css file:

tb-header-image img {
  width: 100%; 
}

You don't need to style img over and over in link function.

Comments

0

I think you should use "ngClass" for directives.

https://docs.angularjs.org/api/ng/directive/ngClass

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.