gpt4 book ai didi

javascript - 如何使用指令添加 css 样式?

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:33 25 4
gpt4 key购买 nike

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

这是我的 html 代码:

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

这是我的指令和 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%',
})

}
}
});

这是我的 backImage.html:

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

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

但我想使用指令 elem.css()

添加如下图所示的样式

enter image description here

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

提前致谢。

最佳答案

否则你可以像那样做 css:

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

希望对你有帮助。

关于javascript - 如何使用指令添加 css 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com