Friday, December 6, 2013

Angularjs list the items from json and click on it show complete details and back to Total list items:

<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="http://code.angularjs.org/angular-resource-1.0.0.min.js"></script>
</head>
<body>
<div ng-app="test">

    <div ng-view></div>

    <!-- CACHE FILE: list.html -->
    <script type="text/ng-template" id="list.html">
        <table class="table table-striped table-condensed">
            <thead>
                <tr><th>Name</th><th>E-mail</th></tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="item in items"
                    data-ng-click="goto_detail(item.id)">
                        <td>{{item.name}}</td>
                        <td>{{item.email}}</td>
                </tr>
            </tbody>
        </table>
    </script>

    <!-- CACHE FILE: detail.html -->
    <script type="text/ng-template" id="detail.html">
        <div>
            <div>Name: {{item.name}}</div>
            <div>E-mail: {{item.email}}</div>
            <div><button class="btn btn-primary"
                    data-ng-click="goto_list()">
                Back To List
            </button><div>
        </div>        
    </script>

</div>

<script>
angular.module('test', []).
config(function($routeProvider) {
    $routeProvider.
    when('/list', {
        controller: ListCtrl,
        templateUrl: 'list.html'
    }).
        when('/detail/:id', {
        controller: DetailCtrl,
        templateUrl: 'detail.html'
    }).
    otherwise({
        redirectTo: '/list'
    });
});

data = [
    {
    id: 0,
    name: "John",
    email: "John@email.com"},
{
    id: 1,
    name: "James",
    email: "James@email.com"},
{
    id: 2,
    name: "Jill",
    email: "Jill@email.com"}
];


function ListCtrl($scope, $location) {
    $scope.items = data;
 
    $scope.goto_detail = function(id) {
        $location.url('/detail/' + id);
    };
}

function DetailCtrl($scope, $location, $routeParams) {
    $scope.item = data[$routeParams.id];

    $scope.goto_list = function() {
        $location.url('/list');
    };
}
</script>
</body>
</html>

Chk the demo:
http://jsfiddle.net/icub3d/daSJ5/4/

No comments:

Post a Comment