What is the best approach to adding components dynamically in AngularJS?

Can someone explain how to create a component in a controller?

I already have an AngularJS module with a controller defined:

let app = angular.module('testApp', []);

However, when I try to load the component, it does not work as expected.

app.controller('MainCtrl', ["$scope", function($scope) {
  // Array of objects containing component details.
  let arr = [{name: 'firstComponent', component: {
      template: "<div>tech filter component</div>",
      controller: [() => {
        let $ctrl = this;
      }]
  }}];
  angular.forEach(arr, (itemArr) => {
    // Component initialization issue here.
    app.component(itemArr.name, itemArr.component)
  });
}]);

This is the HTML code that I am working with:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>angularjs component</title>
</head>
<body ng-app="testApp" >
<div ng-controller="MainCtrl">
  <first-component></first-component>
</div>
</body>
</html>

For more details, you can check out this jsfiddle link.

Answer №1

My suggestion is to avoid dynamically adding components in the manner you are attempting. There is no real advantage to generating components based on an array of objects. However, if you insist on doing it this way, make sure to review your component configuration object and remove the [] near your controller declaration. It's also important to note that arrow functions may not be supported by all browsers that support AngularJS.

Please remember: Components cannot be loaded after calling angular bootstrap.

View

<first-component></first-component>

AngularJS application

var myApp = angular.module('myApp',[]);

let myComponentArray =  [{
  name: 'firstComponent', 
  component: {
  template: "<div>tech filter component</div>",
  controller: function () {
    let $ctrl = this;
  }
}}];


angular.forEach(myComponentArray, function (item) {
  myApp.component(item.name, item.component);
});

> Check out the demo fiddle here.


I recommend creating your components without using a loop. The classic method of defining them will provide better performance and require less code:

View

<first-component></first-component>

AngularJS application

var myApp = angular.module('myApp', []);

myApp.component('firstComponent', {
  template: "<div>tech filter component</div>",
  controller: function() {
    let $ctrl = this;
  }
});

See the demo fiddle for reference

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 button's background color remains the same even after clicking on it

In my exploration of Vue.js, I decided to create a simple project to grasp the concept of class binding. I wanted to add functionality to each button component, so that when a button is clicked, it would change its color or background color to something ot ...

What is the method to transfer a declared object from a .ejs file to my index.js file?

I have a simple script embedded in my .ejs file. The script captures input data from the user and stores it in an object. Now, my goal is to send this object to my index.js file, where I plan to utilize the data with a node module called coap (similar to ...

The issue with mapDispathToProps is that it is failing to assign a function

import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { ShelfModal } from "./shelf-modal"; import { openShelfModal } from "../../../redux/actions/shelf-modal"; export class ShelfTest ex ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

Exploring the `React.createRef` method using Enzyme for testing purposes

Is there a way to test the following class that utilizes the React.createRef API? I couldn't find any examples online. Has anyone attempted this before? How can I mock the ref effectively? My preference would be to utilize shallow. class Main exten ...

Enhance Your Forms with Bootstrap 4 Input Extension

I've been struggling to create a form with Bootstrap 4, specifically setting the value in an input text client-side for a modal form. No matter what I try, it just doesn't seem to work... Here is the form: $('#contact-modal').on(& ...

The value is not being populated in the text area when the onchange event occurs

<textarea className="form-control queryheight box_xp" placeholder="Enter Dashboard Content" type="text" onChange={this.dashboardtextchartchange.bind(this)} value={this.state.textdashboard}> </textarea> Function triggered on change : dashb ...

Is it possible for the r.js optimizer to generate a fresh index.html file that links to the compiled files

After using r.js to optimize my project, I'm wondering how to generate a single index.html file that includes just one optimized script and one CSS file. Would I need to manually write this post-build or is there another way to achieve this? ...

Tips for enlarging an image by tapping on it in handlebars

I currently have the handlebars template engine integrated with node.js, and I'm facing an issue where thumbnail images from the database are displaying at a fixed width and height of 70. Is there a way to enable users to click on these images in orde ...

Struggling to style a nested table using CSS

Please take a look at this JSFiddle example for reference. I am currently working with tablesort and its associated CSS to achieve alternating row colors for the rows containing first and last names. Additionally, I want the rows within the sub-table disp ...

Why is the object not being initialized in a new API call while the string variable is successfully initialized?

There seems to be a basic issue that I am missing, as to why this is happening. GET: example.com/users //returns all data GET: example.com/users?status=1 //returns data with status = 1 GET: example.com/users // this does not work returns the same dat ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

Determine whether an item in a RadGrid is currently in Edit mode using Javascript

Looking for a solution with a telerik RadGrid where I need to determine if a GridDataItem is in edit mode. Preferably using JavaScript. I know how to do this with VB, but I want to achieve it on the client side. Additionally, I would appreciate assistan ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

Is it not recommended to trigger the 'focusout' event before the anchor element triggers the 'click' event?

In a unique scenario, I've encountered an issue where an anchor triggers the 'click' event before the input field, causing it to lose focus and fire the 'focusout' event. Specifically, when writing something in the input field and ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

"Upon subscribing, the object fails to appear on the screen

Why is the subscription object not displaying? Did I make a mistake? this.service.submitGbtForm(formValue) .subscribe((status) => { let a = status; // a = {submitGbtFrom: 'success'} console.log(a, 'SINGLE ...

Creating HTML content in a new window with Vue.js - a step by step guide

Recently, I encountered a problem with jsPDF regarding Unicode support in table generation. To work around this issue, I decided to utilize the browser's print feature instead. I achieved this by creating a new HTML document with the table and display ...

Learn how to create a validation function for phone numbers in a React application that keeps the button disabled until a valid phone number

import React,{useState} from "react"; export default function ValidatePhone() { const [phoneNumber, setPhoneNumber] = useState(""); const [disableButton, setDisableButton] = useState(true); function handleChange(e) { setPho ...

Upgrading Bootstrap from version 3.4 to 5.3 in a .NET project

I have a website project created using .Net Framework 4.7.2. Currently, I am utilizing Bootstrap version 3.4.1 from here. Since Bootstrap 3.4 is now in an end-of-life phase, I need to upgrade to the latest version, 5.3. Upon replacing the old version fil ...