【问题标题】:How can I add css styles using directives?如何使用指令添加 css 样式?
【发布时间】:2016-07-25 16:35:25
【问题描述】:

我正在尝试使用指令动态添加一些 css 样式,我尝试过但有些地方我错过了。

这是我的 html 代码:

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

这是我的指令和控制器:

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%',
      })

    }
  }
});

这是我的 backImage.html:

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

当我像上面那样尝试时,它正在为整个 div 添加样式,如下图所示

但我想使用指令elem.css()添加如下图所示的样式

我正在尝试通过elem.css({}) 添加 css 样式,但是如果图像标记我只想要图像标记的样式并且我也必须像我写 @987654331 时那样从指令中设置 img 标记的样式,它会附加到 div @ 那么这些样式只为 img 标签附加。

提前致谢。

【问题讨论】:

标签: javascript html css angularjs


【解决方案1】:

否则你可以这样做:

<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>

希望能帮到你。

【讨论】:

    【解决方案2】:

    你必须使用.find()

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

    因为elem 是指令元素。所以,你必须找到它的子元素。

    Angular 确实使用了内置的 jQuery 方法,而 .find() 有一个限制,只能通过它们的标记名来查找元素。

    【讨论】:

    • 如果我在同一个指令中使用“img”标签、“h1”和“h2”,那么我如何使用与上面相同的指令编写样式@jai
    【解决方案3】:

    你可以这样做:

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

    或者只是创建一个css文件:

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

    您不需要在链接功能中一遍又一遍地设置 img 样式。

    【讨论】:

      【解决方案4】:

      我认为你应该使用“ngClass”作为指令。

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

      【讨论】:

        猜你喜欢
        • 2013-11-03
        • 1970-01-01
        • 2014-09-25
        • 2014-06-02
        • 2022-01-20
        • 2020-09-08
        • 1970-01-01
        • 2019-03-27
        • 1970-01-01
        相关资源
        最近更新 更多