I'm transitioning from NGJS to NG and trying to recode my previous application to practice.
I stumbled upon the new NgInit where initializations are done in Angular's Component.
What I'm trying to achieve is to initialize a value WITHIN the scope to be used as a toggle to hide and unhide HTML elements.
I'm trying to solve this without looping within ngOnInit() {}
to initialize for each object within the array. (See ng-init
in ng-repeat
block)
Below is a working copy of the scenario I'm trying to achieve:
angular.module("app", [])
.controller("controller", function($scope) {
$scope.init = function() {
$scope.modules = [
{
label: 'Module A',
children: [
'Module A - 1',
'Module A - 2',
'Module A - 3'
]
},
{
label: 'Module B',
children: [
'Module B - 1',
'Module B - 2',
'Module B - 3'
]
},
{
label: 'Module C',
children: [
'Module C - 1',
'Module C - 2',
'Module C - 3'
]
}
];
};
});
.child {
padding-left: 24px;
padding-top: 8px;
padding-bottom: 8px;
}
.parent {
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="controller" ng-init="init()">
<div class="parent" ng-repeat="module in modules" ng-init="toggle=true">
{{module.label}}
<button ng-click="toggle = !toggle">toggle</button>
<span ng-if="toggle" id="child-group">
<div class="child" ng-repeat="child in module.children">
{{child}}
</div>
</span>
</div>
</body>
Here's a Plunker if you prefer: https://plnkr.co/edit/JDBBPLkr21wxSe2dlRBv?p=preview