jacoStillLives jacoStillLives - 2 months ago 19
AngularJS Question

Displaying Json Data from ng-repeat in multiple containers

Hey I have a question about using ng-repeats. I'm trying to display user data from a large json file in two separate containers. When a user clicks on a row it displays the other piece of the ng-repeat in a different section. If someone could take a look at this fiddle and maybe give me a direction to go in that would be awesome. Thanks!

I'm also using ngTable for the table params, but I don't think that has much to do with the issue.

http://jsfiddle.net/cL5aE/1/

HTML:

<body>
<div ng-controller="myController">
<div class="col-md-6">
<table>
<tr ng-repeat="user in $data" ng-click="loadDetails()">
<td>{{user.name}}</td>
<td>{{user.id}}</td>
</tr>
</table>
</div>
<div class="col-md-6">
<tr ng-repeat="user in $data" ng-show="loadDetails()">
<td>{{user.foo}}</td>
<td>{{user.bar}}</td>
</tr>
</div>
</div>
</body>


Controller:

angular.module('app', ['ngTable']);


app.controller('myController', function ($scope, $http, ngTableParams) {

$http.get('http://myjson.com/data.json')
.success(function (data, status) {

$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
CompleteDate: 'asc' // initial sorting
}
}, {
total: data.length, // length of data
getData: function ($defer, params) {
// use build-in angular filter
var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;

$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}

});

});

$scope.loadDetails = function(data) {
//???
}


});

Answer

I would pass the user object as a parameter to a function and assign it a model. That way you don't need to use the ng-repeat in both sections leading to a cleaner and more readable code.

Pass the object you're displaying on the ng-repeat:

<tr ng-repeat="user in $data" ng-click="loadDetails(user)">

Function to load the object to a model property:

$scope.loadDetails = function(user) {
     $scope.viewModel.selectedUser = user;
}

And finally assign the model property to the view:

<table>
  <tr ng-show="viewModel.selectedUser">
     <td>{{viewModel.selectedUser.foo}}</td>
     <td>{{viewModel.selectedUser.bar}}</td>
  </tr>
</table>

http://jsfiddle.net/jimenezjrs/5Cd32/