0

I would like to create a select with your attributes(select id,select class) coming from JSON (that it's defined in my controller).

There is a way to do that? Or Does I need to do dynamic partials with the code of the select?

Assuming I do not know what attributes I have in JSON.

Thanks!

UPDATE:

For example, if I have this JSON:

{ "topology" : [ 
        { "name": "id", "value":"topology_id"  },
        { "name": "class", "value": "topology_class1 topology_class2" },
        { "name": "diasbled", "value": "disabled" } 
    ]
}

I would like to obtain this select tag:

<select id="topology_id" class="topology_class1 topology_class2" disabled="disabled"></select>

And if I have another JSON with another attributes, then these another attributes that will be in my select tag.

1 Answer 1

1

Using your updated JSON file, you can do something like this:

// Your template
<select dynamic-attributes='topology'></select>

// The dynamic attributes directive
angular.module('yourModule')
    .directive('dynamicAttributes', ['jsonData', function (jsonData) {
        return function (scope, element, attrs) {
            // Get the attribute data from a service.
            var attributes = jsonData.get(attrs.dynamicAttributes);
            // Add each of the attributes to the element.
            attributes.forEach(function (attribute) {
                element.attr(attribute.name, attribute.value);
            });
        }
    }]);

// The jsonData service
angular.module('yourModule')
    .service('jsonData', function () {
        // This would really come from the server.
        var json = { 
            "topology" : [ 
                { "name": "id", "value":"topology_id"  },
                { "name": "class", "value": "topology_class1 topology_class2" },
                { "name": "diasbled", "value": "disabled" } 
            ]
        };

        // Public API
        return {
            get: function (name) {
                return json[name];
            }
        };
    });

Here's a working fiddle with the code: http://jsfiddle.net/nfreitas/SmWE8/ (don't mind the styling, it's there to show that the attributes are being added.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer, but try to suppose you don't know what the attributes there are in a JSON. I would like to put all attributes, no matter what the attribute is included in JSON.
Do you have an example of the JSON? If the JSON contains many different types of attributes, then a custom directive would probably be your best option.
I put an UPDATE in my question, please take a look. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.