Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: load partial view into page dynamically

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?

like image 730
user1121487 Avatar asked May 16 '13 13:05

user1121487


1 Answers

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>'
    };
});
like image 147
perry Avatar answered Sep 20 '22 08:09

perry