簡體   English   中英

AngularJS:在指令中獲取KeyValuePairs

[英]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

當然,該指令可能會接受幾個參數,這意味着應將它們全部考慮在內。

我在這里迷路了。

在這種情況下,當您傳遞鍵值配對對象時,您可以簡單地調用JSON.parse然后采用color屬性。

JSON.parse(toggleStyleAttributes).color

如果您指的是ngClass指令的工作方式,它將在后台使用scope.$eval 您可以利用它,但是為了進行這項工作,您需要從表達式中刪除花括號,例如:

data-toggle-style-attribute-on-hover="{'color':contextualGroup.GroupTextColor}"

然后,您應該能夠訪問color屬性,就像使用JSON.parse的情況一樣。

為了將字符串解析為對象,我認為您應該像這樣格式化字符串:

{"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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM