[英]AngularJS: Getting KeyValuePairs in Directive
我目前正在編寫AngularJS指令,當我將鼠標懸停在特定元素上時,該指令允許我設置某些類。
因此,我創建了以下指令:
OfficeUIModule.directive('toggleStyleAttributeOnHover', function() {
return {
restrict: 'A',
link: function(scope, element, attributes){
var toggleStyleAttributes = attributes['toggleStyleAttributeOnHover'];
element.bind('mouseenter', function() {
console.log(toggleStyleAttributes);
});
}
}
})
創建HTML時,我確實將屬性傳遞給了元素,從而允許執行該指令。
如下所示:
data-toggle-style-attribute-on-hover="{'color': {{contextualGroup.GroupTextColor}}}"
當我現在執行頁面時,在瀏覽器的控制台窗口中,確實看到以下輸出: {'color': #cf5c0a}
因此,這看起來不錯,但是現在我需要解析此對象,以便可以添加樣式屬性,說顏色應該是#cf5c0a
當然,該指令可能會接受幾個參數,這意味着應將它們全部考慮在內。
我在這里迷路了。
為了將字符串解析為對象,我認為您應該像這樣格式化字符串:
{"color": "#cf5c0a"}
將鍵和值放入“”。
使用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.