Adding controllers dynamically to ng-includes allows for more flexibility and customization in

How can I dynamically change the controller for ng-include in AngularJS?

In my application, users can create content pages along with controllers. I am able to adjust the ng-include source dynamically, but I am unsure of how to associate a new controller based on user selection. The code snippet below is not functioning as expected:

<div ng-app="MyApp">
    <div ng-controller="ParentController">
        <select ng-model="currentItem" ng-options="item as item.url for item in items track by item.url">
        </select>
        {{ currentItem }}
        <div ng-include src="currentItem.url" ng-controller="currentItem.controller"></div>
    </div>
</div>

The JavaScript code associated with this functionality is as follows:

var app = angular.module("MyApp",[]);

app.controller('ParentController', ['$scope',function($scope){
    $scope.items = [{
        url: 'page1.html',
        controller: 'Page1Controller'
    },
    {
        url: 'page2.html',
        controller: 'Page2Controller'
    }];
    $scope.currentItem = {};
}]);

app.controller('Page1Controller', ['$scope',function(){
    alert('Page1');
}]);

app.controller('Page2Controller', ['$scope',function(){
    alert('Page2');
}]);

Answer №1

To solve this issue, I opted to utilize a directive:

<div ng-include src="currentItem.sourceUrl" dyn-controller="currentItem.controllerName"></div>

Here is the JavaScript Directive code snippet:

app.directive('dynController', ['$compile', '$parse', function($compile, $parse) {
  return {
    restrict: 'A',
    terminal: true,
    priority: 100000,
    link: function(scope, element, attributes) {
            // Extract and parse the controller name from the scope
            var controllerName = $parse(element.attr('dyn-controller'))(scope);
            element.removeAttr('dyn-controller');
            element.attr('ng-controller', controllerName);

            // Compile the element with the ng-controller attribute
            $compile(element)(scope);       
  };
}]);

The key approach in this solution is monitoring attribute alterations, introducing ng-controller, and then compiling the element.

Special thanks to:

How to watch property in attrs of directive

as well as

Dynamic NG-Controller Name

Answer №2

Contained in this array are plain objects featuring two fields: url and controller, both with string values.

 $scope.items = [{
        url: 'page1.html',
        controller: 'Page1Controller'
    },... ]

To reference the function, utilize the $injector service.

While this approach may work, it is unclear why you're not leveraging the ParentController to modify the object in your array (or a directive).

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

Encountering an Axios Error 404 while attempting to save my information to the MongoDB database

I am encountering an Axios error 404 when trying to register details in a MongoDB database. The error message I am getting is - "Failed to load resource: the server responded with a status of 404 (Not Found)." You can view the Error 404 Image for reference ...

Issues encountered while attempting to verify password confirmation within a React form using Joi

I have been struggling to implement a schema for validating a 'confirm password' form field. While researching how to use Joi for validation, I noticed that many people recommend using the Joi.any() function. However, every time I attempt to use ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

Using Knex to Generate a Migration Including a Foreign Key

I attempted to use the code from this link in order to create a foreign key: how to do knex.js migration However, an error occurred at this line of code: table.bigInteger('AddressId') .unsigned() .index() .inTable('Address&apos ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Show a pop-up window when a button is clicked, just before the page redirects

Is there a way to display a popup message before redirecting to another page when clicking on a button? Here's the scenario: <a href="addorder.php?id=<? echo $row01['id']; ?>" ><button id="myButton" class="btn btn-primary btn ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Tips on including the Elastic Search JavaScript client library in Node.js controller files

Currently, I'm working on a node.js project using the express framework and creating a RESTful API. My next step is to integrate elastic search into my application. I've started by installing the elastic search JavaScript client library and addin ...

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Nodejs App cannot be started locally due to a directory import issue

My journey to deploy my app on Heroku has hit a roadblock. The import statements, like import cors from 'cors', are causing the app to fail in production with the "Cannot Load ES6 Modules in Common JS" error. Interestingly, everything runs smooth ...

Retrieve and manipulate custom headers from a webview within an AngularJS app

I have implemented an angular application within a webview using the following code: WebView.loadUrl(String url, Map<String, String> additionalHttpHeaders) In order to manage the content and display it appropriately, I am maintaining a state in my ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

How can Express JS be configured to make URL calls from a local environment?

I encountered an issue with my code (Weather App using OpenWeatherMap Api) when I attempted to move my apiKey and apiUrl to the .env file. An error appeared in the terminal, but it's unclear why it occurred. Below is my code: const express = require( ...

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

Looking to develop a dynamic JSON preview feature using AngularJS

Below is an example of JSON data: data: [{ test: { innertest: "2345", outertest: "abcd" }, trans: { sig: "sou", trip: [{ one: "2" }, { two: "3" }], otherac: "iii" },{ test: { innertest: "uuu", ...

Exploring AngularJS: Effiecient Looping and Styling

Being a beginner in AngularJS, please excuse me if this question seems silly. I want to display my data in a grid format (using Ionic) where each row has separate columns like this: <div class="row"> <div class="col-33">Item 1</div> ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...