简体   繁体   中英

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.

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.

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}

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

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(toggleStyleAttributes).color

If you're referring to the way the ngClass directive works, it uses scope.$eval under the hood. 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.

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

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);
            });
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM