Tuesday, December 10, 2013

AngularJS Learning Notes 1 - Views and Routing

For normal html page, if open a URL, server will find out the individual html page to show. But for angularjs, it will dynamically render individual html page as a div for the tag "ng-view".


  • This is a sample folder structure:

/rest
     | - css
     |- img
     |- js
          | - app.js
          |- controllers.js
          |- directives.js
          |- filters.js
          |- services.js
     |- lib
          |- angular
                |- angular.js
     |- partials
          |- home.html
          |- page1.html
          |- page2.html


  • home.html to define ng-view
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My App</title>
</head>
<body>
 
  <div id="container-main" ng-view> </div>

  <script src="lib/angular/angular.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>
</body>
</html>
  • app.js to define router
'use strict';
//define a module which will be used throughout the article.
var mymodule = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']);
// configure the router
mymodule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    $routeProvider.when('/page1', {templateUrl: 'partials/page1.html', controller: 'MyCtrl1'});
    $routeProvider.when('/page2', {templateUrl: 'partials/page2.html'});
    $routeProvider.otherwise({redirectTo: '/home'});
  }]);

  • controllers.js
'use strict';
function MyCtrl1(){}
  • Testing
After deploy to tomcat, open the following URLs to test

http://localhost:8080/rest/#/home
http://localhost:8080/rest/#/page1
http://localhost:8080/rest/#/page2


Reference website:
http://docs.angularjs.org/tutorial/step_07

No comments:

Post a Comment