Angular - Utilizing controllers without any associated HTML elements and utilizing broadcasted events

My situation is a bit peculiar. I have a controller that I need to manage when a dialog opens. I am utilizing ngDialog along with templates and directives. Below is the code for DialogController:

(function() {
    'use strict';

    angular.module('Common').controller('DialogController', DialogController);

    DialogController.$inject = ['$scope', 'ngDialog'];

    function DialogController($scope, ngDialog) {
        $scope.$on('openDialog', open);

        function open(which) {
            ngDialog.open({
                template: which,
                className: 'newproductdialog'
            });
        }
    }

})();

Essentially, the purpose of this controller is solely to handle the opening, closing, and other functionalities of ngDialog.

Now, here is the approach I take to trigger the opening of the dialog (via vm.navigate invoked through ng-click) in HomeController:

    function initNav() {
        /**
         * Array of navigation items.
         * @type {{name: string, id: string, selected: boolean, icon: string}[]}
         */
        vm.navs = [{
            name: 'Home',
            id: 'home',
            selected: true,
            icon: 'ss-home'
        }, {
            name: 'New',
            id: 'create-new-product',
            selected: false,
            icon: 'ss-addfile'
        }];
        /**
         * Color of the navigation elements.
         * @type {string}
         */
        vm.color = '#ea8daf';

        /**
         * Navigation function triggered upon clicking a nav item.
         * @param item {object} The $scope.navs object that was clicked.
         */
        vm.navigate = function(item) {
            switch(item.id) {
                case 'create-new-product':
                    ----->$rootScope.$broadcast('openDialog', 'newproduct');
                    break;
            }
        };
    }

Finally, here is the corresponding HTML for the above method:

<ft-nav items="homeCtrl.navs" onselect="homeCtrl.navigate" color="homeCtrl.color"></ft-nav>

Despite my efforts, this approach does not seem to be effective. I am contemplating if the lack of associated HTML for DialogController is causing the issue. Could it be a problem with how I am using the broadcast event? While I am aware that employing a service and having DialogController watch the service is an option, I feel that utilizing $broadcast is a more preferable route. Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

That's absolutely right. The DialogController will not execute unless it is specifically mentioned on a DOM element using the ngController directive.

Instead of declaring a controller, you can utilize a .run block.

app.run(function ($rootScope, ngDialog) {
  /* ... */
});

The code included in the .run will be executed immediately without requiring any associated DOM.

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

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

The dictionary of parameters has an empty entry for the 'wantedids' parameter, which is of a non-nullable type 'System.Int32', in the 'System.Web.Mvc.JsonResult' method

The console is showing me an error stating that the parameters dictionary contains a null entry for parameter wantedids. I am trying to pass checked boxes to my controller using an array, so only the admin can check all boxes of tips for a specific user. T ...

"Although both jQuery and PHP are capable of setting the element attribute, it is only PHP that functions successfully

I have been trying to set an element attribute to adjust the range of a slider. Initially, I used ajax to fetch data from a php file and assign it to the attribute. The slider looked good with the value but unfortunately, it wasn't functioning as expe ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file: cons ...

Exploring Node.js with a straightforward illustration and tackling the EPERM error

const server = require('http').createServer(function(req, res){ }); server.listen(8080); This code snippet is causing an error to be displayed in the console: $ node node_server.js node.js:201 throw e; // process.nextTick error, or &apos ...

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...

What is the best way to transfer Kendo Grid row data to a Kendo popup window within a partial view using jQuery?

I am currently facing a challenge in passing the row data from the Kendo Grid to a partial view that is displayed through a Kendo popup window. Within the partial view, users have the option to upload an image file related to the specific row record. This ...

Tips for accessing the parent reference while binding using the .on() method

I needed to attach an event like this $("div").on("click", "li",function() { var div= $(this).parent().parent(); //this is what i'm using //..... }); above the <div> <ul> <li>1</li> <li>e2</l ...

Creating a real-time clock in a single line console log format using NodeJS

To create a live clock in a single line display within a browser, we can utilize setInterval and manipulate the content inside an HTML element like so: var span = document.getElementById('span'); function time() { var d = new Date ...

When comments are submitted via AJAX, they are displayed twice, but upon reloading the page, they only appear once

After using the codes below to add a comment to a post and display it without refreshing the page, I encountered an issue where the comment is displayed twice instead of once. However, the comment is only saved once in the database. Interestingly, when the ...

Exploring the mysteries of AngularJS ng-repeat with dynamic key-value pairs

My challenge is to create a table using Angular ng-repeat without knowing the keys in advance. When working with an API, I receive an Array of Objects. Each object has unique and unspecified keys. https://i.stack.imgur.com/bW0RL.png Within my HTML, I a ...

Applying an active class in VueJs to a specific li element within a v-for loop when clicked

Struggling to select (set active class) in a v-for loop when one class is already selected. Here's the code and an explanation: These are my available subscriptions, with one already selected based on user data <ul> <li v-for="(s, key, ...

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...

Utilizing variables in GraphQL requests

UPDATE: see the working code below GraphiQL Query I have this query for retrieving a gatsby-image: query getImages($fileName: String) { landscape: file(relativePath: {eq: $fileName}) { childImageSharp { fluid(maxWidth: 1000) { base64 ...

Troubleshooting the issues with implementing cross-browser jscrollpane functionality

Hey there! I've been exploring this tool to customize the default scroll-bar, and here's a fiddle showcasing my experimentation. In the fiddle, I've included the following code snippet <div class="scroll-pane horizontal-only">(located ...

Could JavaScript scope be compromised by the use of jQuery/Ajax?

Important: Although I have found a workaround for this issue, I am still puzzled as to why the initial method did not work for me. In my HTML file, I have a jQuery script designed to send a number to a server using an ajax request. Here is the structure o ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...