简体   繁体   中英

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:

<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 在此处输入图片说明

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

在此处输入图片说明

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.

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.

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.

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.

I think you should use "ngClass" for directives.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM