Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular js nested controllers list/item

I am new to angular and wanted advice on the best route to achieve something like this. This jsFiddle doesn't work but here is the idea.

I want tabs along the top with items available for selection. When you select the item, the data is populated below.

I wanted to have a ListController and an ItemController, so i can separate out the methods that act on the list vs that act on the item; since i wanted the items to be updatable directly. I am getting all the data on the page load, so i don't want to load each tab dynamically.

How can i do this and/or how can i fix the fiddle or new fiddle? jsFiddle plunker

<div ng-app="myApp">
  <div ng-controller="ListController">
    <ul class="nav nav-pills">
      <li ng-repeat="artist in list">
        <a show-tab="" ng-href="" ng-click="select(artist)">{{$index}} - {{artist.name}}</a>
      </li>
    </ul>
    <div ng-controller="ItemController">
      <p>{{name}} - {{selected.name}}</p>
      <span>{{totalSongs}}</span>
      <span>{{selected.songs.length}}</span>

      <ul>
        <li ng-repeat="song in selected.songs" ng-controller="ItemController">{{song}} - {{totalSongs}}</li>
      </ul>
    </div>
  </div>
</div>

I would really like to keep the controllers separate and logic separate.

like image 571
dre Avatar asked May 08 '13 00:05

dre


1 Answers

I created some functionality in the ItemController to illustrate how you could act on them separately: http://jsfiddle.net/jdstein1/LbAcz/

Added some data to the list controller:

$scope.list = [{
    name: "Beatles",
    songs: [{
        title: "Yellow Submarine",
        time: "424"
    }, {
        title: "Helter Skelter",
        time: "343"
    }, {
        title: "Lucy in the Sky with Diamonds",
        time: "254"
    }]
}, {
    name: "Rolling Stones",
    songs: [{
        title: "Ruby Tuesday",
        time: "327"
    }, {
        title: "Satisfaction",
        time: "431"
    }]
}];

And fleshed out the item controller:

app.controller('ItemController', ['$scope', function ($scope) {
    $scope.selectItem = function (song) {
        $scope.song.time++;
    };
}]);
like image 138
jdstein1 Avatar answered Nov 12 '22 18:11

jdstein1