Struggles with loading angular.js controller are arising

My challenge in AngularJS is related to injecting controllers using the ui.router resolve. The issue I'm facing is that the template loads before the controller, causing an error when trying to access the controller. Here's a snippet of my app.js:

var app = angular.module('app', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('view1', {
            url: "/view1/",
            templateUrl: "view1/view1.html",
            resolve: {'': appendStaticFileToPage("view1/view1.js")}
        })

        .state('view2', {
            url: "/view2/",
            templateUrl: "view2/view2.html",
            resolve: {'': appendStaticFileToPage("view2/view2.js")}
        })

    ;

    function appendStaticFileToPage(file) {
        return function($q){
            var script = document.createElement('script');
            script.setAttribute('src', file);
            document.getElementsByTagName('head')[0].appendChild(script);
        };
    }

});

Although I successfully inject the JavaScript file when a user clicks on a link, the template defined in templateUrl always loads first. As a result, the controller is not yet available, leading to console errors. How can I resolve this issue?

For a simplified version of my code, you can check out:

http://plnkr.co/edit/X9uFOMIJq5tCn7VezSzT?p=preview

I'm looking for a solution to make sure the controller is loaded before the template and prevent any console errors.

EDIT

In my earlier approach, I used promises in the append code as shown below:

function appendStaticFileToPage(file) {
    return function($q){
        var deferred = $q.defer();

        var script = document.createElement('script');
        script.setAttribute('src', file);
        document.getElementsByTagName('head')[0].appendChild(script).ready(function(){
            deferred.resolve();
        });

        return deferred.promise;
    };
}

However, with this method, nothing happens - the template doesn't load and no console.log messages from the controllers are displayed.

Answer №1

After encountering issues with registering the controller using .controller, I decided to try a different approach. Instead of that, I injected the $controllerProvider service and registered the controller through it, which turned out to be successful.

app.config(function($stateProvider, $urlRouterProvider, $controllerProvider) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('view1', {
            url: "/view1/",
            templateUrl: "view1.html",
            resolve: {'': appendStaticFileToPage("view1.js", "MyViewOneController")}
        })

        .state('view2', {
            url: "/view2/",
            templateUrl: "view2.html",
            resolve: {'': appendStaticFileToPage("view2.js", "MyViewTwoController")}
        })

    ;

    function appendStaticFileToPage(file, controllerName) {
        return function($q){
            var deferred = $q.defer();

            var script = document.createElement('script');
            script.onload = function () {
                $controllerProvider.register(controllerName, window[controllerName])
                deferred.resolve();
            };
            script.onerror = function () {
                deferred.reject();
            };
            script.setAttribute('src', file);
            document.getElementsByTagName('head')[0].appendChild(script);

            return deferred.promise;
        };
    }

});

Additionally, I made updates to view1.js and view2.js as shown below:

'use strict';
window.MyViewOneController = function($scope) {
  console.log("Got to view 1");
};

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

The error message that is popping up on Windows when running `npm start` is

Hey there! I'm having an issue with my Windows 10 installation and Mean. After installing express, I tried to start npm using the command "npm start" but encountered the following error: C:\>npm start npm ERR! Windows_NT 6.3.9600 npm ERR! arg ...

Decode PDF417 barcode images with ease using HTML and JavaScript on both desktop and mobile web browsers

Looking to utilize JavaScript to decode PDF417 type barcode images? If you're encountering Zxing plugin issues in mobile browsers but it works well on desktop browsers with https://github.com/PeculiarVentures/js-zxing-pdf417, consider alternative sol ...

nodemon encountered an error and is currently on standby for any updates before restarting

UPDATE Upon further investigation, I have discovered that both gulp and grunt are experiencing issues in this application as well as the default installation of mean.js. This is while running the app locally on a Mac. Interestingly, when I start either app ...

Ways to retrieve information from a $$state object

Everytime I try to access $scope.packgs, it shows as a $$state object instead of the array of objects that I'm expecting. When I console log the response, it displays the correct data. What am I doing wrong? This is my controller: routerApp.controll ...

Is it beneficial to dockerize an AngularJS + nginx codebase?

Currently, I am working on an AngularJS front-end project that is hosted on nginx and communicates with a back-end Java server (which is not part of this codebase). Each time I need to install the package, I run the following commands: # ensure that node, ...

There was an error that was not properly handled: The property 'Minus' cannot be read because it is undefined

I tried uninstalling and reinstalling NPM using the command npm install but encountered an error afterwards. I also attempted npm audit fix --force which resulted in the following error: An unhandled exception occurred: Cannot read property 'Minus&a ...

What's the deal with Mongoose and preloading data?

There is an issue I am facing with regards to retrieving a document from mongodb. In my node.js server configuration, I have the following call: app.get('/ruimtes/:afkortingCampus', function (req, res) { Ruimtes.find({'campusAfkorting&apo ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

Leveraging AngularJS and PhoneGap for seamless Facebook login/SDK integration even without the need for a server

In the process of developing a web application that will be deployed with Phonegap, I am utilizing NodeJS on the backend and AngularJS on the frontend, incorporating Facebook authentication. Currently, the Node server is running at localhost:3000 (will eve ...

Verify the identity of all REST API requests without the need for a username or password in order to obtain a

I have a unique setup where I am selling products. The API fetches product data from a centralized node back-end and displays it on an angular front-end that is hosted on multiple domains. The challenge I'm facing is the need to authenticate all reque ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

The live streaming feature in Node.js is currently experiencing issues with the streaming-s3 function

I have successfully implemented the streaming-s3 node-modules on my local machine. However, when I try to use it on a live server where HTTPS is enabled, it does not seem to be working properly. Interestingly, if I disable HTTPS on the live server, the fi ...

Creating a node server that will intercept all requests from an Angular frontend (using http) and route them to a

Currently, I am utilizing express on node for routing and incorporating Angular as the front-end framework. Additionally, Redis is being used for session management. My objective is to ensure that whenever an HTTP request is made from Angular, it first goe ...

How can a connection between on-premise AngularJS-based single page applications and AWS cloud servers be established?

Here's a question that might seem basic to some, but it's worth exploring: How can you structure your system so that your single-page application is hosted on premise under a specific hostname like mydogs.com, while also hosting your application ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...

What are the steps for hosting an AngularJS application or M.E.A.N. client-side app on an Apache or NodeJS server?

After completing a MEAN stack app with basic CRUD functionality, I successfully hosted the server side API built in nodejs. However, I am currently facing challenges when it comes to hosting the client side UI. The UI is constructed using angularjs and ...

Secure your website with a two-tier authentication system: passports for users logging in with Facebook and local

Currently, I am in the process of developing a website using the node and express framework for the back end, with angular handling the front end. To handle user authentication, I have implemented passport so that users can sign up or log in using only the ...

Difficulty connecting to the API endpoint in AWS

I created a two-tier MEAN application with the authentication API backend hosted on AWS EC2 and the Angular front-end hosted on AWS S3 as a static site. During development, I ran the auth backend using node/express on http://localhost:5719/. For the front ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Express app: the ideal location to implement a closed-loop temperature control system

I am relatively new to working with express.js, having only created some basic client/server apps in the past. Currently, I am looking to develop a temperature controller using a PID component. However, I am struggling to grasp the architecture of express ...