ng-controller does not function properly when assigned a variable as its parameter

Every time I attempt to insert a variable into the ng-controller parameter, I receive the following error message:

" Error: [ng:areq] Argument 'curController' is not a function, got string

    <div  ng-include="templates[selected-1]" ng-controller='curController'>

controller

  for(i=0;i<$scope.cours.length;i++){
    switch($scope.cours[i].type){
        case "c1":
        $scope.controllers[i]="cours1Display"
        $scope.templates[i]="views/cours/cours1.html"
        break;
        case "c2":
        $scope.controllers[i]="cours2Display"
        $scope.templates[i]="views/cours/cours2.html"
        break;
        case "c3":
        $scope.controllers[i]="cours3Display"
        $scope.templates[i]="views/cours/cours3.html"
        break;
        case "c4":
        $scope.controllers[i]="cours4Display"
        $scope.templates[i]="views/cours/cours4.html"
        break;
        case "exo1":
        $scope.controllers[i]="exo1Display")
        $scope.templates[i]="views/exos/exo1Decorator.html"
        break;
        case "exo2":
        $scope.controllers[i]="exo2Display"
        $scope.templates[i]="views/exos/exo2Decorator.html"
        break;
        case "exo3":
        $scope.controllers[i]="exo3Display"
        $scope.templates[i]="views/exos/exo3Decorator.html"
        break;
    }

curController =   $scope.controllers[0]

$scope.pageChanged=function(){
    alert($scope.selected)
    curController =   $scope.controllers[$scope.selected-1]
}

Answer №1

Have you attempted using brackets? It's important to assign 'curController' to $scope.curController.

<div  ng-include="templates[selected-1]" ng-controller='{{curController}}'>

It appears that Angular does not natively support dynamic controller names, but you have the option to create a custom directive to define your own controller.

angular.module('app', [])
  .directive('myController', function($controller) {

    return {
      restrict: 'A',
      priority: 600,
      scope: true,
      link: function(scope, element, attr) {
        console.log(scope, element, attr);
         var locals = {
              $scope: scope,
              $element: element,
              $attrs: attr,              
            };
         element.data('$myController', $controller(attr['myController'], locals));
      }
    };

  })
  .controller('CustomController', function($scope) {
    console.log($scope);
    $scope.value = 'My custom value in my custom controller.'
  })

;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="app" ng-init="curController='CustomController'">
  <div my-controller="{{curController}}">value={{value}}</div>

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

How to render a div in HTML with full CSS styling applied

I'm currently working on a project using asp.net MVC. My goal is to print a div with all the CSS styles applied, which may contain one or more nested divs. Despite trying various JavaScript print codes, I have not been successful. The page I want to p ...

When the scope changes, the AngularJS variables in the view are not updating accordingly

Recently diving into AngularJS has been quite the journey for me. However, I've hit a major roadblock that's had me stumped for the past two days. Here's my dilemma: Despite updating the variable in the controller, my view refuses to reflec ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Utilizing AngularJS: Conditionally rendering ngIf within an array of objects containing unique properties

Facing a challenge with the ngIf directive that I have been struggling to resolve despite trying various solutions. In my scenario, I have an array of objects, each containing different properties. The structure is as follows: object = [ { ...

Issues with connecting to Socket.IO in Cordova app

I'm having troubles setting up my Cordova app to establish a socket.io websocket connection. Despite following the instructions I found, it doesn't seem to connect when running in debug mode. Can anyone help me troubleshoot this issue? Server Si ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Does the Error page in Next JS 13 fail to properly manage fetch API errors?

After referencing the documentation for Next.js with app router, I followed the instructions to create an error.tsx page within my app folder (app/[lang]/error.tsx). This file contains the code provided in the docs. Additionally, I included some API calls ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Responsive Tabs with Material-UI

Can MUI's Tabs be made responsive? This is what I currently have: https://i.stack.imgur.com/KF8eO.png And this is what I aim to accomplish: https://i.stack.imgur.com/b3QLc.png ...

The ViewChild instance is currently undefined

Within my component, I have the following setup: @ViewChild('PaginatedTableComponent') userTable: PaginatedTableComponent; Here is the corresponding HTML code inside the component: <pag-paginated-table #userTable [(shouldUpdate)]="sh ...

Effortlessly switching back and forth between OData and WebAPI in breezejs

I find myself in a bit of a complex situation. My application requires access to two different services: one is an ODATA service, and the other is a WebAPI (with Breeze controller) service. The architecture of my application revolves around AngularJS modu ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Displaying saved locations on Google Maps API

Recently, I delved into experimenting with the Google Maps API and AJAX integration. While I encountered various challenges along the way, I managed to overcome them. However, I've hit a roadblock now. I was following a well-written and detailed tuto ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

Blocking of Node.js Promises

I am currently new to Node/JS and am working on developing a password recovery page for an existing IT portal. The page involves searching through AD (ldap) and a DB where users have registered. The goal is to present users with options to authenticate and ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

Incorporating graphics into a React component

Currently exploring React JS and looking to dive into the practical side of things. Following a documentation tutorial that constructs a basic comment system. I've replicated the component structure outlined in the tutorial: PostBox PostList Pos ...

Transform a Mongoose object into a specific JSON schema

When retrieving data from MongoDB using mongoose as an ORM, I have a specific requirement. Instead of sending all the fetched information back to the client in the response, I need to convert the mongoose object into a JSON object that adheres to my cust ...

Transitioning NodeJS from local development to a live website

After successfully creating a site using NodeJS with one-page HTML/jQuery, everything is functioning properly on localhost. However, I am facing issues when trying to put the site online at www.xxxx.com. I already have a registered .com domain, but I am un ...