In my AngularJS 1.6 application, there is a widget section that allows the end user to customize 3 widgets. The user can select from a list of available widgets and decide where to place them.
Each widget is a component initialized like this:
(
function(angular) {
function Module1Controller() {
var vm = this;
// other stuff here
}
angular.module("app")
.component(
"module1", {
controller: Module1Controller,
templateUrl: 'module1.html'
}
);
}
)(angular)
The data for rendering the widgets comes from a webservice, and I need to be able to activate one component and deactivate the rest based on the data.
My initial approach was to create a controller like this:
(
function(angular) {
function ModulesController() {
var vm = this;
vm.firstModule = 1;
vm.secondModule = 1;
vm.thirdModule = 1;
vm.availableModules = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
angular.module("app")
.controller(
"ModulesController",
[
ModulesController
]
);
}
)(angular)
The HTML structure for rendering the widgets is as follows:
<div class="container-fluid" ng-controller="ModulesController as c">
<div class="row">
<div class="col-xs-4"> <!-- third widget area -->
<module-1 ng-if="c.firstModule == 1"></module-1>
<module-2 ng-if="c.firstModule == 2"></module-2>
...
<module-10 ng-if="c.firstModule == 10"></module-10>
</div>
<div class="col-xs-4"> <!-- third widget area -->
<module-1 ng-if="c.secondModule == 1"></module-1>
...
<module-10 ng-if="c.secondModule == 10"></module-10>
</div>
<div class="col-xs-4"> <!-- third widget area -->
<module-1 ng-if="c.thirdModule == 1"></module-1>
...
<module-10 ng-if="c.thirdModule == 10"></module-10>
</div>
</div>
</div>
While this approach works, it is not scalable. If I have a large number of widgets, I would have to duplicate code for each one. I considered using ng-include
but it doesn't load the accompanying controller.
A provided Plunker demonstrates the desired functionality: https://plnkr.co/edit/uO8SUcmNMOGHcPjc1lWs?p=preview
By changing the combo value, the corresponding module is replaced. The question remains: is there a more efficient way to activate a component based on a controller field in AngularJS 1.6 without relying on ng-if
for each component?