Select AngularJS Controller based on Attribute

I am currently developing a dashboard using AngularJS and have implemented a "widget" directive. The issue I am facing is that the widget can belong to one of several types, which is determined by a specific property within the directive. When it comes to templates, retrieving the attribute from the attributes object in the link function and compiling it is straightforward.

However, when it comes to the controller, I find it more challenging (or perhaps I am overlooking something). The current approach I have taken is as follows:

return ['$compile', '$http', function($compile, $http) {
    var templateContent = '';

    return {
        restrict: 'A',
        scope: {},
        link: function($scope, element, attributes, controller) {
            element.append($compile(templateContent)($scope));
            ...
        }
    };
}];

I am searching for a way to dynamically set the controller based on an attribute within the element. Is this achievable? I prefer not to explicitly define data-ng-controller on the element as I aim to only specify the TYPE of widget in the HTML without concerning myself with the template location or controller.

My ideal scenario would resemble something like this:

<div data-widget="typename">...</div>

Answer №1

Creating a dynamic dashboard using AngularJS can be approached in multiple ways. Personally, I dealt with a similar issue when building a drill-down-able dashboard.

One simple approach is to use a naming convention. By concatenating the widget name with a specific suffix like "Controller," you can dynamically assign controllers using an ng-controller attribute and then compile it in your directive.

Alternatively, you can create a service called "widgetControllers" to map each widget type to its corresponding controller. In your directive, you can retrieve the controller name from this service.

Another suggestion is to consider creating a directive for each type of widget instead of a controller/template combination. A generic-widget directive can dynamically generate elements based on the widget type, utilizing either the naming convention or the service-dictionary approach. This allows for nesting widgets within each other, making it more flexible.

If you require more clarification or would like a demonstration of these concepts, feel free to reach out.


UPDATE

For those requesting an example, you can find one here.

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 am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

A more detailed explanation of Angular's dot notation

I came across a solution for polling data using AngularJS here on stackoverflow. In this particular solution (shown below), a javascript object is used to return the response (data.response). I tried replacing the data object with a simple javascript arra ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

How to properly display an Angular Template expression in an Angular HTML Component Template without any issues?

When writing documentation within an Angular App, is there a way to prevent code from executing and instead display it as regular text? {{ date | date :'short'}} Many sources suggest using a span element to achieve this: <span class="pun"&g ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

How to determine if a variable has been declared in JavaScript but not assigned any value

Is there a way to check if a variable has been declared but not assigned a value? I've looked at similar questions and they all seem to recommend using typeof myVar !== 'undefined' However, this always returns false because even when decl ...

Creating a full-screen loading animation that appears when a button is clicked is a great way to enhance user experience. This animation can flow seamlessly from right to left before disappearing, providing a visually engaging transition for users as they

Despite anticipating more negative responses than positive ones, I believe that even one correct answer outweighs it all! So, I'm trying to figure out how to create a loading animation that covers the entire screen whenever a button on the navigation ...

Personalized bar graph description using Highcharts

Looking to create a unique stacked Highcharts bar chart with custom text within each bar, but currently only seeing the data number displayed by Highcharts. Check out the fiddle here. Here's the code snippet: $(function () { $('#container& ...

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Buttons for displaying and concealing content are unresponsive

After spending over 6 hours trying to fix this code and searching online, I am completely frustrated. My goal is to hide the login table and its associated background image (#lg #ck) and instead, place a button on top of where the login table is. When thi ...

Unlocking the secrets of capturing key presses before submitting with jQuery

I'm seeking help with creating an app that scans a barcode and displays the data on screen. I prefer not to use textboxes in order to prevent data editing. Currently, I have set up the enter key to be automatically sent at the end of the barcode scan ...

Angular js: Understanding the use of "this" within the ng-if function

Is there anyone who can assist me with the following question: How do I access the "this" element within the ng-if (in my example, the classname is "class_to_obtain" of the span element)? http://plnkr.co/edit/0s7PCWN2fJ8sJpFSJssV HTML ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

What is the best way to showcase data from input fields within a bootstrap modal dialog?

After the user has entered their details and clicks submit, I would like to present the information in a Bootstrap modal with a confirmation button below. This serves as a preview of the data before it is saved to the database. Here's what I have so ...

The continuous firing of the postback event of the Asp.Net Button is

Why does the postback event keep firing for my button? Strangely, when I try to debug with Firebug and set a break point on the function(e) part, the code seems to skip right over it. Even using return false doesn't seem to resolve the issue. <sc ...

Class methods cannot be invoked within their constructor

I'm currently facing challenges with implementing my express router. This is a "subrouter" of my main router, hence I need to extend express.Router. Here's an example of the code (simplified to include only one method): import express from "expr ...

How to resolve: Preventing Ajax - Post request from executing repetitively

I am facing an issue with a table that is formatted using the Datatables script. There is a column in the table which contains icons for actions. When a user clicks on an icon, a modal is loaded and its content is fetched using the POST method. The modal ...

Steps for correctly displaying a success message after clicking and copying to the clipboard:

In the process of developing a color palette, I am incorporating a clipboard icon enclosed in a Tooltip component alongside each color. The functionality involves copying the color's name to the user's clipboard upon clicking the icon. Subsequent ...