2

Tell me please, how to create component in controller?

I have angularjs module with controller

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

And i try to load component but it is not load.

app.controller('MainCtrl', ["$scope", function($scope) {
  // I have an array with objects.
  let arr = [{name: 'firstComponent', component: {
      template: "<div>tech filter component</div>",
      controller: [() => {
        let $ctrl = this;
      }]
  }}];
  angular.forEach(arr, (itemArr) => {
    // Why it doesn't init from here ?
    app.component(itemArr.name, itemArr.component)
  });
}]);

And it is my html

<!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>

jsfiddle link

1 Answer 1

1

I really do not recommend to dynamically add components the way you try it. There is no benefit generating your components based on an array of objects. But .. if you really want to do it this way you should check your component configuration object and remove the [] near your controller declaration. Also note that arrow functions are not supported by all browsers which are supporting AngularJS.

Note: You can't load components after angular bootstrap has been called.

View

<first-component></first-component>

AngularJS application

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

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


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

> demo fiddle.


I would prefer to not use a loop to create your components. You should do it by using the classic way by definition. It will give you more "performance" and less codes:

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;
  }
});

demo fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

I write small library and i need to load component dynamically, thanks, i'll check it
Yes, it works, but i want to load components from controller.
You can't load components after angular bootstrap has been called.
@tetramaster glad to help ya. I pushed you a bit. Please don't forget to mark right answer if you agree with my aproach. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.