Reputation: 567
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>
Upvotes: 2
Views: 4162
Reputation: 18392
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.
<first-component></first-component>
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:
<first-component></first-component>
var myApp = angular.module('myApp', []);
myApp.component('firstComponent', {
template: "<div>tech filter component</div>",
controller: function() {
let $ctrl = this;
}
});
Upvotes: 1