Obtain the Present Controller Identity within AngularJS

Currently, I am working on developing a directive that can create a grid dynamically. The code I have written functions properly but there is one limitation where I need to explicitly mention the controller name 'DemoCtrl'. I am wondering if there is a way to automatically retrieve the current controller name from within the directive so that I can pass it to the buildColumn/buildRows functions for improved flexibility and efficiency?

angular.module('app').controller('DemoCtrl', function ($scope) {
    $scope.controller = "DemoCtrl";
    $scope.coldata = [
        {name: 'Account'},
        {name: 'Name'}
    ];
    $scope.rowdata = [
        {
            "account": "ABC",
            "name": "Jim"
        },
        {
            "account": "DEF",
            "name": "Joe"
        },
        {
            "account": "GHI",
            "name": "Fred"
        }
    ];
});

angular.module('foxy.components.grid', [])

        .controller('GridController', ['$scope', '$attrs', function ($scope, $attrs) {
            }])

        .directive('grid', function ($compile) {
            return {
                restrict: 'EA',
                controller: 'GridController',
                require: "^ngController",
                scope: {
                    data: "=",
                    columns: "=",
                    controller: "="
                },
                link: function (scope, element, attrs, ctrl) {
                    scope.$watch('data', function () {
                        var el = $compile(buildGrid(scope.controller))(scope);
                        element.replaceWith(el);
                        element = el;
                    });

                }
            };
        })

function buildGrid(controller) {
    var html = "<table>";

    html += "<thead>";
    html += buildColumn(controller);
    html += "</thead>";

    html += "<tbody>";
    html += buildRows(controller);
    html +="</body>";

    html += "</table>";

    return html;
}
function buildColumn(controller) {
    try {
        var html = "";
        var dom_el = document.querySelector('[ng-controller="' + controller + '"]');
        var ng_el = angular.element(dom_el);
        var ng_el_scope = ng_el.scope();
        var colname = ng_el_scope.coldata;

        html += "<tr>";

        for (i = 0; i < colname.length; i++) {
            html += "<th>";
            html += colname[i]["name"];
            html += "</th>";
        }

        html += "</tr>";

        return html;
    } catch (err) {
        return "#error" + err;
    }
}

function buildRows(controller) {
    try {
        var html = "";
        var dom_el = document.querySelector('[ng-controller="' + controller + '"]');
        var ng_el = angular.element(dom_el);
        var ng_el_scope = ng_el.scope();
        var colname = ng_el_scope.coldata;
        var rows = ng_el_scope.rowdata;

        for (j = 0; j < rows.length; j++) {
            html += "<tr>";

            for (data in rows[j]) {
                html += "<td>";
                html += rows[j][data];
                html += "</td>";
            }

            html += "</tr>";
        }

        return html;
    } catch (err) {
        return "#error" + err;
    }
}

Answer №1

To obtain the controller name, simply utilize your route service

{{$route.current.scope.name}}

Answer №2

After some consideration, I made a modification to my code by introducing a fresh scope variable associated with the controller name that is then transmitted to the buildGrid function. Although not perfect, this adjustment has proven effective!

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

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

What is the best way to patiently wait for a promise to fulfill, retrieve its value, and pass it to another function?

I am facing an issue with getting the value of stringReply into my app.post method in Express. From what I understand, it seems like the code is fully executed before the promise is resolved, resulting in an undefined value when attempting to log stringR ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

Using a line to plot data in Highcharts instead of an area chart

Currently, I am experimenting with the highcharts demo provided in the documentation using highcharts-ng. I am attempting to create area charts, but unfortunately, when I execute the code, only the line is displayed without the desired area. Below is a s ...

Encountering a "SyntaxError: Unexpected token '/' in... index.ejs while compiling ejs" issue following the recent npm package updates

After upgrading EJS from version 2.7.4 to 3.1.5 along with some other packages in my project, I am encountering a problem where I can no longer access any of the webpages. Instead, an error is being thrown on every page. Additionally, after the update, I s ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...

Creating Dynamic Divs in ASP.NET

Attempting to dynamically create a Div by clicking a button has been a challenge for me. I found a helpful link here: After referring to the link, I created the following code on the server side (.cs page): public static int i = 0; protected void Bu ...

Exploring the indexOf method in Jade

Currently using Jade and Express. '#{value.users}' is an array data type. '#{user.username}' is a string data type. Attempting to utilize the if '#{value.users}'.includes('#{user.username}') method. When true, I ...

Issue encountered while generating REST API through Postman resulting in a 500 error

I am in the process of creating a Node.js API for a web application. The GET request is functioning properly, however, when attempting to execute a POST request, I encounter an error messageError Below is the code snippet: //User Schema const mongoose ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Exploring the interaction of karma, jasmine, Angular, and UI router through testing the resolve function when using state.go with parameters

In my Angular module "moduleB", I have the state defined as shown below: $stateProvider .state('stateB', { parent: 'stateA', abstract: true, templateUrl : base ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Utilizing VueMq for personalized breakpoints and module inclusions

In my main app.js, I set and define breakpoints by importing the VueMq package. import VueMq from 'vue-mq'; Vue.use(VueMq, { breakpoints: { xsmall: 500, small: 768, medium: 1024, large: 1360, x ...

Express: simplifying the use of middleware for app implementation

I am looking to update the code in my index.js file app.use(require('sass-middleware').middleware({ src: path.resolve(__dirname, '../'), dest: path.resolve(__dirname, '../public') })); app.use(require('browserify-dev ...

retrieve fresh information from the API

Hello! I am attempting to retrieve new data from an API by filtering it with a JSON file. My goal is to filter the data from the API using the JSON file and extract any new information. const jsnf = JSON.stringify(fs.readFileSync("./data.json" ...

What could be causing the JQuery date picker to fail to load on the initial ng-click event?

I am encountering an issue with a JQuery UI date picker that is loaded through ng-click using the code below: Input: <input type="text" id="datepicker" autocomplete="off" ng-model="selectedDate" ng-click="showDatepicker()" placeholder="(Click to sele ...

Struggling with overlaying Bootstrap modals on top of each other

This idea is inspired by the topic Multiple modals overlay I am working on developing a folder modal that allows users to either 1) open an existing file or 2) create a new file within each folder modal. To see how it functions, please run the code below ...