Angular JS Magazine

duminică, 24 august 2014

Selecting Partial Views Dynamically

The ng-include directive can be the perfect choice to dynamically add pieces of HTML code. Per example, the below code will allow us to display some data in a tabular structure or in a list. We can switch between list and table with a simple checkbox.

The data displayed in a table:

<table class="table">
    <tr ng-repeat="item in atp">

Same data displayed in a list:

    <li ng-repeat="item in atp">

Main page that allows us to switch between table and list:

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../angular/angular.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet" />
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet" />
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                    $scope.includePieceOfHTML = function () {
                        return $scope.showWhat ? "list.html" : "table.html";
<div ng-app="atpModule" ng-controller="atpCtrl" ng-init="atp=[
     { name: 'Nadal, Rafael (ESP)', rank: 1 },
     { name: 'Djokovic, Novak (SRB)', rank: 2 },
     { name: 'Federer, Roger (SUI)', rank: 3 },
     { name: 'Wawrinka, Stan (SUI)', rank: 4 },
     { name: 'Ferrer, David (ESP)', rank: 5 }]">

    <div id="atpPanel" class="panel">
        <h3 class="panel-header">ATP SINGLES RANKINGS</h3>
        <div class="well">
            <div class="checkbox">
                    <input type="checkbox" ng-model="showWhat">
                    Show the list
        <ng-include src="includePieceOfHTML()"></ng-include>