gpt4 book ai didi

css - 在指令模板内绑定(bind)样式值

转载 作者:行者123 更新时间:2023-12-03 21:38:57 25 4
gpt4 key购买 nike

我有这个指令:

app.directive('MessageChild', function($timeout) {
return {
restrict: 'E',
scope: {
pos: '=?',
msg: '='
},
link: function(scope, element, attr) {
scope.msg = attr.msg;
scope.styleVar = "100" //I want to insert this variable
},
template: '<style> div {position: absolute; top: **<scope variable or binding here>** }</style>' +
'<div>{{msg}}</div>'

})

这只是展示我正在尝试做的事情的一个例子。我的风格实际上要复杂得多,并且涉及动画。我需要执行一些操作,然后将值传递给我的样式。如何从我的指令中在此位置注入(inject)变量? Angular 不喜欢我将绑定(bind)放在样式中。

最佳答案

您可以尝试在 link 中构造一个对象。函数,然后可以将其传递给 ngStyle 指令。

app.directive('messageChild', function($timeout) {
return {
restrict: 'E',
scope: {
pos: '=?',
msg: '='
},
link: function(scope, element, attr) {
scope.msg = attr.msg;
scope.styleVar = {
'color': 'blue',
'position': 'absolute',
'top': '100'
};
},
template: '<div ng-style="styleVar">{{msg}}</div>'
};

});

示例 Plunker:

http://plnkr.co/edit/b1uO8N

编辑

您可以使用 <style> 完成相同的操作。如果您愿意,请标记:
app.directive('messageChild', function($timeout) {
return {
restrict: 'E',
scope: {
pos: '=?',
msg: '='
},
link: function(scope, element, attr) {
scope.msg = attr.msg;
scope.styleVar = 'blue';
},
template: '<style> div {position: absolute; top: 100; color: {{styleVar}}}</style><div>{{msg}}</div>'
};

});

示例 Plunker:

http://plnkr.co/edit/8NxKFS?p=preview

关于css - 在指令模板内绑定(bind)样式值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863060/

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