Creating my first AngularJS app.
A ng-repeat:er loads titles. Each title is clickable. When clicking a title, an ajax-call is getting more JSON data. I need to add this data below the clicked title.
The normal way, I would create the HTML as a string and append it to the source code. But since I'm using AngularJS, there should be a way to create a partial view with the HTML and another ng-repeat in it.
How can this be done?
I would use a directive as per @Nicolas suggestion. Combining this with what @Andrew suggested you could do something like this.
Controller:
.controller('MainCtrl', function ($scope, $http) {
$scope.items = [
{id: 'a', subItems: []},
{id: 'b', subItems: []}
];
$scope.getSubItems = function(id) {
$http.get('/sub-items/' + id)
.then(function() {
$scope.items.subItems = $scope.items.subItems.push(response.data);
});
}
});
View:
<div ng-repeat="item in items">
<a ng-click="getSubItems(item)">{{item.id}}</a>
<list sub-items="item.subItems"></list>
</div>
Directive:
.directive('list', function() {
return {
restrict: 'E',
scope: {
subItems: '=subItems'
},
template: '<ul>' +
'<li ng-repeat="subItem in subItems">{{subItem.id}}</li>' +
'</ul>'
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With