gpt4 book ai didi

css - Angular JS : Can we assign custom CSS to an HTML element more than once in a directive?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:15 25 4
gpt4 key购买 nike

我创建了一个自定义指令,其目的是将 base64 字符串和文件扩展名作为背景图像动态分配给 <div>。将用作用户个人资料照片。相关代码如下:

app.directive('backImg', function() {
return {
link: function(scope, element, attrs) {
scope.$watchGroup(['profilePictureStr', 'profilePictureExt'],
function(newValues, oldValues, scope) {
element.css({
'background-image': 'url(data:image/' +
scope.profilePictureExt + ';base64,' +
scope.profilePictureStr + ')',
'background-size':'contain',
'background-repeat':'no-repeat',
'background-position':'center'
});
});
}
};
});

这里是 <div>我想通过指令动态控制其 CSS:

<div back-img>

我目前观察到的是,第一次调用 watch 时,在加载时,element.css()调用成功。但是,在页面加载时范围变量 profilePictureStrprofilePictureExt尚未分配,并且是空字符串。此后不久,页面进行 REST 调用以检索与登录用户对应的 base-64 图像字符串。但是,第二次 watch 被调用时,element.css()通话似乎没有坚持。代码确实实际上被调用了,但 CSS 似乎没有变化。

是否无法通过 Angular 指令多次动态更改 DOM 中的 CSS?在这一点上,我倾向于将所有内容都放入 style 中。 <div> 的属性有问题,但如果可能的话,我更愿意使用指令来执行此操作。

最佳答案

试试这个

app.directive('backImg', function() {
return {
link: function(scope, element, attrs) {
scope.$watchGroup(['profilePictureStr', 'profilePictureExt'],
function(newValues, oldValues, scope) {

if (scope.profilePictureExt && scope.profilePictureStr) {

element.css({
background: 'url("data:image/' + scope.profilePictureExt + ';base64,' + scope.profilePictureStr + '") contain no-repeat center'
});


}

});
}
};
});

关于css - Angular JS : Can we assign custom CSS to an HTML element more than once in a directive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159986/

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