Encountering an issue with AngularJS where the controller is not being registered when combining ocLazyLoad and ui-router

Struggling with implementing ocLazyLoad in my project, I keep encountering this Angular error

Error: $controller:ctrlreg A controller with this name is not registered

The 'eventoCtrl' controller is not registered.


NOTE: Utilizing ui-router for defining app states as well.

ANOTHER NOTE: Any alternative suggestions for routes or lazy loading methods are welcome.


app.js

(function(){
angular
    .module('kulchr', [
      'ui.router',
      'oc.lazyLoad'
    ]);})();

config.js

angular
.module('kulchr')
.config(function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
  $stateProvider
  .state('eventos', {
    url: '/eventos',
    views: {
      'top-menu-nav': {
        templateUrl: 'templates/top-menu-nav.html',
      },
      'main': {
        templateUrl: 'templates/eventos.html',
        controller: 'eventoCtrl as listaEvento',

        resolve: {
          eventoCtrl: function ($ocLazyLoad) {
            return $ocLazyLoad.load(
              {
                files: ['controller/listaEventoController.js'
                       ,'service/eventoService.js']
              });
          }
        }

      }
    }
  });
  $urlRouterProvider.otherwise('/');
});

controller

(function() {
    'use strict';

    angular
        .module('kulchr')
        .controller('eventoCtrl', ListaEventoController);

    ListaEventoController.$inject = ['servicoEvento'];

    function ListaEventoController(evento){
        var vm = this;

        var promise = evento.buscaDados();

        promise.then (function(response){
            vm.eventos = response.data;
        })

    }
})();

service

(function() {
    'use strict';

    angular
        .module('kulchr')
        .service('servicoEvento', Evento);

    function Evento($http, $q) {
        var d = $q.defer();
        var self = this;

        $http.get('/mockup-data/eventos.json')
            .then(function (response){
                d.resolve(response);
            }, function(reason) {
                console.log("Motivo: " + reason.data +
                            "Status: " + reason.status +
                            " - " + reason.statusText);
                return $q.reject(reason);
            });


        self.buscaDados = function(){
            return d.promise;
        }
    }

})();

Any idea what I might be overlooking? Consulted the ui-router documentation but it only added to my confusion

By the way, all works smoothly when directly adding files to index.html using .

Answer №1

At this moment, the issue lies in the fact that your listaEventoController has not been properly loaded when the named view is being rendered. This problem stems from incorrectly placing the resolve object. It should not be used at the named view level, but should instead be moved outside and placed after the url (flatten property) within the state definition object.

By relocating the resolve block, the oc-lazyLoad module will handle the downloading of the listaEventoController and eventoService files from the server, ensuring that the downloaded services are registered within the Angular context and available for use throughout the application.

Code

$stateProvider
.state('eventos', {
    url: '/eventos',
    views: {
      'top-menu-nav': {
        templateUrl: 'templates/top-menu-nav.html',
      },
      'main': {
        templateUrl: 'templates/eventos.html',
        controller: 'eventoCtrl as listaEvento'
      }
    },
    //resolved moved out of "named view" object.
    resolve: {
       eventoCtrl: function ($ocLazyLoad) {
          return $ocLazyLoad.load({
                files: [
                  'controller/listaEventoController.js',
                  'service/eventoService.js'
                ]
             }
          );
       }
    }
})

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

Is the setInterval function in JavaScript only active when the browser is not being used?

I am looking for a way to ensure proper logout when the browser is inactive using the setInterval() function. Currently, setInterval stops counting when the browser is active, but resumes counting when the browser is idle. Is there a way to make setInterv ...

Using Vue to implement a "v-model" on a custom component that incorporates the ace-editor

Snippet CustomEditor.vue: <template> <div class="custom-container"> <div class="custom-editor" ref="editor"></div> </div> </template> <script> import ace from 'ace-builds' import 'ace- ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

Tips for incorporating numerous visible arrows into your Three.js project by utilizing the THREE.ArrowHelper functionality

edited: specifying the use of ArrowHelper I am looking to create a multitude of arrows on a 2D plane to visually represent a vector field. Typically, there are around 20,000 vectors that need to be displayed. Although I am currently using THREE.ArrowHelp ...

collaborative data interchange in angularjs controllers

When it comes to managing shared state between controllers, I often struggle to find the best approach among the many options recommended on forums like Stack Overflow. To help clarify my thoughts, I've created a simple diagram outlining my basic idea ...

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

Convert the string to a time format of hours and minutes (hh:mm)

I am currently working with an input field that requires a time value to be entered. The format for the Time field is in hh:mm on the 24-hour clock format, such as 7:30, 11:45, 16:10, 19:11, or 22:43. <input id="szReminderTime" type="text" value="" max ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Could there be a contrasting directive to the angular `ngInit` directive?

There is a single element that toggles visibility based on the ng-if condition. <div ng-if="level <= vm.receivedLevelsAmountToShow" ng-init="addTimeLineComponentData(vm.item)" > <div>{{item.id}}</div> </div> ...

Using infoWindows with multiple markers in Google Maps

i have developed a custom Google Maps application that pulls data from a CSV file. The functionality works well, but I am facing an issue with the infoWindow when looping through all the objects. It seems like the problem stems from the marker variable bei ...

Guide to initiating a node.js socket.io server through a brackets extension

I am currently working on developing a brackets extension that involves sending data to a server. What I aim to do is execute a server.js file from my main.js file, which will create a node.js socket.io server. Once this server is set up, the extension sho ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

Troubleshooting the EACCESS error in Node.js on OpenShift

I'm having trouble getting the application to start properly, as I keep receiving an EACCESS error: Error: listen EACCES Below is the code snippet causing the issue: var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080 var server_ip_address ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

When transferring files using formData via axios, the server is unable to interpret the data

`` In my quest to figure out how to send a file from a client using an input type=file to an API, I came across the suggestion to use formData. Following some examples I found, I implemented this approach, but upon checking the data on the server side, it ...

Introduce a brief 7-second pause prior to triggering the customized modal in the JavaScript variable

Is there a way to make the below variable activate after waiting for 7 seconds? My attempt at chaining didn't work. $(function(){ var inst = $.remodal.lookup[$('[data-remodal-id=modal]').data('remodal')]; inst.open(); }); ...

Generate a base64 encoded string from a file and send it as a response using an ASP.NET httpHandler after receiving an AJAX request

Looking for a way to download various file types using AJAX. I came up with the idea of sending get requests with the file name as a query string via AJAX, receiving the response as a base64 string, and then converting it into a blob object to be download ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...

Saving the AJAX response object in a global variable - Important fields are not being retrieved

Currently, I am developing an asynchronous webpage in Grails wherein I invoke a controller and display the response as a D3.js network. To ensure further usability, I saved the object as a global variable. Despite the successful execution of the function u ...