[英]AngularJS: Getting KeyValuePairs in Directive
I'm currently writing an AngularJS directive that allows me to set certain classes when I hover on a specific element. 我目前正在编写AngularJS指令,当我将鼠标悬停在特定元素上时,该指令允许我设置某些类。
Therefore, I've created the following directive: 因此,我创建了以下指令:
OfficeUIModule.directive('toggleStyleAttributeOnHover', function() {
return {
restrict: 'A',
link: function(scope, element, attributes){
var toggleStyleAttributes = attributes['toggleStyleAttributeOnHover'];
element.bind('mouseenter', function() {
console.log(toggleStyleAttributes);
});
}
}
})
When I create my HTML, I do pass an attribute to my element, allowing this directive to be executed. 创建HTML时,我确实将属性传递给了元素,从而允许执行该指令。
This looks like the following: 如下所示:
data-toggle-style-attribute-on-hover="{'color': {{contextualGroup.GroupTextColor}}}"
When I execute my page right now, in the console window of my browser, I do see the following output: {'color': #cf5c0a}
当我现在执行页面时,在浏览器的控制台窗口中,确实看到以下输出:
{'color': #cf5c0a}
So, this looks quite good, but now I need to parse this object so that I can add a style atribute saying that the color should be #cf5c0a 因此,这看起来不错,但是现在我需要解析此对象,以便可以添加样式属性,说颜色应该是#cf5c0a
Off course, this directive might accept several parameters, meaning that they should all be taken into account. 当然,该指令可能会接受几个参数,这意味着应将它们全部考虑在内。
I'm a bit lost here. 我在这里迷路了。
In this case as you're passing in a key-value paired object you could simply call JSON.parse
and then take the color property. 在这种情况下,当您传递键值配对对象时,您可以简单地调用
JSON.parse
然后采用color属性。
JSON.parse(toggleStyleAttributes).color
If you're referring to the way the ngClass directive works, it uses scope.$eval
under the hood. 如果您指的是ngClass指令的工作方式,它将在后台使用
scope.$eval
。 You could make use of that but in order to make that work you'd need to remove the curly braces out of the expression, like: 您可以利用它,但是为了进行这项工作,您需要从表达式中删除花括号,例如:
data-toggle-style-attribute-on-hover="{'color':contextualGroup.GroupTextColor}"
You should then be able to access the color property, much like in the case if you'd used JSON.parse. 然后,您应该能够访问color属性,就像使用JSON.parse的情况一样。
To parse string to object, i think you should format string like that: 为了将字符串解析为对象,我认为您应该像这样格式化字符串:
{"color": "#cf5c0a"}
Put key and value into "". 将键和值放入“”。
Using 2-way bindings instead of attributes 使用2向绑定而不是属性
angular.module('MyApp', []).directive('toggleStyleAttributeOnHover', function() {
return {
restrict: 'A',
scope: {
config: '=toggleStyleAttributeOnHover'
},
link: function(scope, element){
element.bind('mouseenter', function() {
element.css('color', scope.config.color);
});
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.