Thursday, February 05, 2015

Angular JS: how to use separate html to layout the web app

different html to show different UI of the web app. 

HTML: 

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
        <input type="text" ng-model="name"/> {{name}}
        <div>
            {{age}}
        </div>
        <ul>
            <li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
            <li><a href="#/ThirdPage">third page</a></li>
        </ul>
        <div ng-view><!-- the content from other html file will display here --></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>


JS:

var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.controller('MyController', function($scope){
    console.log("MyController");
    $scope.hello = "Hello from AngJS";
    $scope.customers = ["dave", "larry"];
    $scope.age = 20;
    
    $scope.message = 'This is a new screen';
    
    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        $scope.message = special;
    };
});

//Define Routing for app
demoApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/SecondPage', {
        templateUrl: 'second.html',
        controller: 'MyController' // can be different controller. will instantiate new controller. different scope
    }).
      when('/ThirdPage', {
        templateUrl: 'third.html',
        controller: 'MyController
// can be different controller. will instantiate new controller. different scope
      }).
      otherwise({
        redirectTo: '/SecondPage'
      });
}]);

second.html:

<div>{{message}} </div> <!-- can add other HTML tag -->

third.html:

<div>{{hello}} </div> <!-- can add other HTML tag -->

No comments: