In Angular, link a freshly loaded ".js" controller to a newly loaded "html" view following the bootstrapping process on ngRoutes

As a newcomer to Angular, I have been experimenting with loading dynamic views using ngRoutes (which is very cool) along with their respective .js controllers for added functionality. However, I am encountering difficulties in binding them together after bootstrap has already occurred.

For instance, I have a view located at "../partials/inicio.php" and its controller at "/assets/js/partials/inicio/inicio.js", both of which are not loaded prior to bootstrap. To ensure they are loaded when the URL tag is "/", I have implemented the following method in main.js: (and it successfully loads them).

main.js

  app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
      .when("/", {templateUrl: "../partials/inicio.php", 
            resolve:{
              load: function($q, $route, $rootScope) {

                var deferred = $q.defer();

                var dependencies = [
                  '/assets/js/partials/inicio/inicio.js'
                ];

                $script(dependencies, function () {
                  $rootScope.$apply(function() {
                    deferred.resolve();
                    console.log("The promise has resolved.");
                  });
                });
                console.log("The promise was made.");
                return deferred.promise;
              }
            }
          })  

assets/js/partials/inicio/inicio.js

  app.controller('inicio', function ($scope) {
     console.log("Controller responds from the INSIDE in inicio.js");
  });

  console.log("Controller responds from the OUTSIDE in inicio.js");

../parcials/inicio.php

 <script>console.log("View is loaded in inicio.php");</script>

 <div class="container" id="inicio" ng-controller="inicio">
 </div>

Upon observing the console logs, you will see that they render as shown in the following snapshot: Console output

While the view and controller are loaded in the "correct order" (controller first, then the view), an error occurs as the view attempts to find the ng-controller "inicio".

How can this binding be achieved? How do I "register" the controller post-bootstrap and link it to the view?

Important considerations:

  • I prefer not to preload the controller or its declaration.

  • If modules need to be added or dependencies referenced (e.g., ControllerProvider), it is crucial to understand where and when these actions should take place.

Your insights on this matter are greatly appreciated!

Answer №1

Consider including the controller field in the route config. This eliminates the need to use ng-controller as it will be automatically assigned to the template:

$routeProvider
  .when("/", {templateUrl: "../partials/inicio.php", 

        // specifying a controller for the view
        controller: 'inicio',

        resolve:{
          // loading dependencies
        }
      })  

Instead of using ng-controller, utilize ng-view. Place this within your main HTML file (index.html or index.php).

<div class="container" id="inicio" ng-view>
</div>

This sequence ensures that scripts are loaded first before assigning a controller to the view. As a result, partials will be loaded into the div with the ng-view directive when the route changes.

Additional Note

If you ever require a controller to be applied across all partial views (e.g., navbar controller in index.html), simply include a script tag for this specific controller. Other controllers can then be dynamically loaded within the resolve section of the route configuration.


Further Insight

Despite numerous attempts to investigate the issue, I encountered the same error. However, I have a potential solution involving a different script loading library called ocLazyLoad which I successfully utilized in a previous project (). After integrating ocLazyLoad into your project, follow these steps:

Step 1

Add the 'oc.lazyload' module to the app module, e.g.,

angular.module('app', ['oc.lazyload'])

Step 2

Modify the resolve section as follows:

//...

resolve:{
    load: function($ocLazyLoad) {
         var dependencies = [
              '/assets/js/partials/inicio/inicio.js'
         ];

         return $ocLazyLoad.load(dependencies);
}
//...

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

Implementing a feature in React where the active class is applied only to the next element upon clicking

I'm just starting out with React and working on a custom menu bar project. The Mobile menu includes 2 dropdown submenus, which I want to toggle open and close by clicking an arrow. Currently, the arrows are functioning, but when I click on one arrow, ...

Tips for verifying the "truthiness" of an object, removing any falsy values, and making changes to the object

I am faced with the task of examining each property of an object to determine if it is truthy, and then removing any that are not. var user = { name: 'my name', email: null, pwHash: 'U+Ldlngx2BYQk', birthday: undefined, username: &ap ...

Executing an external JavaScript function from within an internal JavaScript code block

Currently, I am dealing with 2 JavaScript blocks. One is contained within my HTML and handles touch functionality, while the other is an external file serving as a content slider. My goal is to utilize touch events to control the slider - allowing users to ...

Switch up the Yii ListBox default onChange event to utilize AJAX with onClick instead

Below is the code I have for a <select> element: $htmlOptions = array( 'size' => '20', 'ajax' => array( 'type' => 'POST', 'url' => Y ...

Assessing attributes within the templateUrl

I'm trying to retrieve the value of an attribute within the templateUrl function of my directive. <my-dirc type="type"></my-dirc> In my directive (my-dirc), the code looks like this: return { scope : { type : = }, templateUrl ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

The value returned by $(this).next() is undefined

I'm struggling to implement jQuery functionality to toggle the display of a div, but I am encountering an issue where my jQuery code is unable to select it. Every time I try, it returns undefined. Can anyone provide assistance? $(document).on(&apos ...

An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of th ...

Inject JSON data into a JavaScript array

I am dealing with a JSON file in the following format: [{"excursionDay":"2"},{"excursionDay":"3"},{"excursionDay":"4"}] My goal is to extract the values of excursionDay and store them in an array in JavaScript like this: dayValues = [2,3,4] Here is m ...

Tips for transferring information from controller JavaScript to view JavaScript within AngularJS

Currently, I am working on an angularJS application where I retrieve data from a REST service within the controller. The retrieved data is then passed to the view using $scope. However, I encountered an issue when trying to use this data in my in-page Java ...

Tips on retrieving the URL of a background image using "$event.target" to display in an Ionic modal

How can I display the clicked image in a modal? Implementation: <a ng-click="openModal($event)" ng-style="{'background-image': 'url(assets/img/img-01.jpg)'}"><img src="assets/alpha-4x3.png"></a> <a ng-click="openM ...

Do we really need to implement ajax in this code snippet?

In my scenario, I have two JSP files named test1.jsp and test2.jsp. The flow of my program goes like this: I need to retrieve data from a textbox in test1.jsp, but the Ajax call is initiated from a different page. My objective is to receive the controller ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

Having trouble with CSS values not being applied to dynamically injected HTML div elements in Angular 4?

Link to Codepen My Angular calendar application runs smoothly without any errors. However, I am encountering an issue where the CSS styles are not being applied to the page. When I implemented this separately, everything worked fine. But as soon as I inc ...

Extracting data from XPath results reveals information beyond just the elements themselves

Having trouble using the getElementsByXPath function in CasperJS to return a specific string from an xpath I determined. Despite my efforts, it seems like the function is only returning data for the entire webpage instead of the desired string. var casper ...

What is the reason behind functions not requiring (args) when called with parameters?

Have you ever noticed the difference in behavior between these two code snippets? var foo = document.getElementById("foo"); foo.addEventListener("keydown", foo); function foo(e){ console.log(e.keyCode); } And this one: var foo = docum ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

What is the reason behind 'continue' not functioning properly in an Angular forEach loop?

I have a particular issue with my Angular app. I am using an angular.forEach function and trying to skip some values by using the continue keyword, but for some reason it's not working as expected. <div ng-app="app"> <div ng-controller="te ...