Construct a drop-down menu using properties extracted from a JSON file in AngularJS

Is there a way to dynamically create a select element using attributes such as select id and select class from a JSON object defined in my controller, without knowing the specific attributes beforehand?

Can this be achieved without resorting to dynamic partials with hardcoded code for each select element?

If I do not have prior knowledge of what attributes are present in the JSON object.

Thank you!

UPDATE:

For example, if the JSON data looks like this:

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

I would like to generate the following select tag:

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

Subsequently, if another JSON object contains different attributes, those attributes should populate the select tag accordingly.

Answer №1

To utilize the updated JSON file, implement the following approach:

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

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

// Service handling JSON data
angular.module('yourModule')
    .service('jsonData', function () {
        // Typically fetched from a server.
        var json = { 
            "topology" : [ 
                { "name": "id", "value":"topology_id"  },
                { "name": "class", "value": "topology_class1 topology_class2" },
                { "name": "diasbled", "value": "disabled" } 
            ]
        };

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

View the functioning demo on this fiddle: http://jsfiddle.net/nfreitas/SmWE8/ (ignore the styling showcasing the added attributes.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

How can an Angular module/component be displayed independently as well as embedded within another module/component?

Imagine I have a module called ModuleA with a router entry as follows: path: 'modulea', loadChildren: './modulea/modulea.module#ModuleA' Introducing ComponentA (with selector component-a) Now, let's talk about ModuleB and its ro ...

Import a new JavaScript file and access a variable

I'm currently working on a school project where I am creating an online platform for purchasing games. The platform is designed using HTML, CSS, and JS, with each game having its own corresponding JS file containing the information. Here is a sample o ...

Using only the $http.get method, you can easily retrieve data in a simple

Here is my message from JSP, I am attempting to extract information from the response. $http.get('url.jsp', data).then(successCallback, errorCallback); I encountered an issue with "data is not defined" https://i.sstatic.net/NX60Y.png Is there ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: https://i.sstatic.net/M0G1W.png Take a look at my file structure: https://i.sstatic.net/nVsUX.png I considered usi ...

Typescript implementation for structuring JSON response data from API calls

As a beginner in Typescript, I am eager to create a straightforward weather application using Firebase functions. One of the initial steps involves making an API call to fetch the current temperature of a particular city. Upon making the API call, the JSO ...

Properly removing an object from a THREE.js scene while still preserving it in the HEAP

Is there a correct way to remove mesh from a scene without causing memory leaks? removable_items = []; box = new THREE.Object3D(); scene.add(box); function add() { var mesh = new THREE.Mesh( new THREE.IcosahedronGeometry( 10, 5 ), ...

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Strategies for filtering fields in LoopBack based on the included model

Here is my query that I am working on: UserModel.find({ filter: { include: [ "communications", "roles" ], where : { "object_type" : 1 } } }, function(data){ $root ...

Revamping the Backbone collection by resetting and parsing data

In my Backbone application, I have a view that renders when a collection is reset. I am fetching data from the server and resetting the collection with this fetched data. However, I'm facing an issue where the values I retrieve from the server are sho ...

Callback function for Jeditable when the form is reset

My situation involves having a string with multiple lines separated by line breaks, which is then parsed into an <ul> hierarchy using JavaScript on the client side. The editing of this list is done using Jeditable, where the user sees the original te ...

Implementing a Global Timezone Setting for the Entire Application

Currently, I am focusing on Timezone settings within my application. My goal is to adjust the default timezone that the browser automatically selects when... let date = new Date() The function provides the date and time based on the browser's timezon ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

Failed to fetch http://localhost:8000/Stack/script.js due to network error 404 in Django project

As I embark on creating a simple to-do app, I encountered an error while trying to implement some JavaScript on the homepage. The error in question is highlighted above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404). Being new to integra ...

Instead of pressing "w" to walk, simply click on the A-frame screen

I am diving into the amazing possibilities of A-frame. I've successfully implemented the WASD controls, which are working great. However, I am looking to enhance the experience by replicating the function of the W button when clicking on the screen, s ...

Keeping an Rxjs observable alive despite encountering errors by simply ignoring them

I am passing some values to an rxjs pipe and then subscribing to them. If there are any errors, I want to skip them and proceed with the remaining inputs. of('foo', 'bar', 'error', 'bazz', 'nar', 'erro ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

Utilizing JavaScript to verify the presence of a div element within dynamically injected HTML code

While working on a website, I have implemented an embed function which involves calling a javascript from my server to inject HTML on another remote server. To ensure that these embeds also benefit from Google ranking, I have included a piece of HTML in t ...