James James - 1 month ago 6
AngularJS Question

AngularJS - Ng-repeat Clickable divs to reveal child records

$scope.webAppsDepartment = [
{ AppName: 'Unlock Case', Colour: '#AF1A3F', Apps: null },
{ AppName: 'Route Rec', Colour: '#00ABA9', Apps: null },
{ AppName: 'RW Database', Colour: '#AF1A3F', Apps: null },
{ AppName: 'Standing Order', Colour: '#00ABA9', Apps: null },
{ AppName: 'EA Department', Colour: '#000000', Apps: [
{ AppName: 'EA Payments', Colour: '#F1BA21', Apps: null },
{ AppName: 'Print Route', Colour: '#00ABA9', Apps: null }
]
}
];


If I have the above object and the parent items are bound to be displayed in divs using ng-repeat. How can I then click on each parent item to then replace the parents with the children records of the clicked div?

Almost want to change the ng-repeat.

<div class="col-md-4" ng-repeat="a in webAppsDepartment | filter:filteredApp">
<div class="link-box" ng-style="{'background-color': a.Colour}">
<span ng-click="webAppsDepartment = {{a.Apps}}" title="{{a.AppName}}" data-toggle="tooltip" data-placement="bottom">
<img src="~/Content/Images/base-jumping-64.png" />
</span>
</div>
</div>


Thanks,

Answer

ng-click="webAppsDepartment = {{a.Apps}}" is not going to work. What you'd want to do is instead save a reference to the children when clicking it. See the updated ng-click We use a function and pass whichever selected item and then display the children

https://jsfiddle.net/vadaqjjv/1/

<div class="col-md-4" ng-repeat="a in webAppsDepartment | filter:filteredApp">
  <div class="link-box" ng-style="{'background-color': a.Colour}">
    <span ng-click="selectDept(a.Apps)" title="{{a.AppName}}" data-toggle="tooltip" data-placement="bottom">
      <img src="~/Content/Images/base-jumping-64.png" />
    </span>
  </div>
</div>
<div ng-if="selectedDepartment">
  <span>Selected department</span>
  <div ng-repeat="dept in selectedDepartment">
    {{dept.AppName}}
  </div>
</div>

Your controller:

app.controller('TestCtrl', function($scope) {
  $scope.webAppsDepartment = [
      { AppName: 'Unlock Case', Colour: '#AF1A3F', Apps: null },
      { AppName: 'Route Rec', Colour: '#00ABA9', Apps: null },
      { AppName: 'RW Database', Colour: '#AF1A3F', Apps: null },
      { AppName: 'Standing Order', Colour: '#00ABA9', Apps: null },
      { AppName: 'EA Department', Colour: '#000000', Apps: [
              { AppName: 'EA Payments', Colour: '#F1BA21', Apps: null },
              { AppName: 'Print Route', Colour: '#00ABA9', Apps: null }
          ]
      }
  ];
  $scope.selectedDepartment = null;
  $scope.selectDept = function(dept) {
    if (dept != null) {
      // do something here to show your children
      $scope.selectedDepartment = dept;
    } else {
      $scope.selectedDepartment = null;
    }
  }
});
Comments