Shalvin Interests

Wednesday, October 14, 2015

AngularJS for .Net Developers : Routes and AngularJS Seed

Just like Asp .Net MVC AngularJS too have Routes.
In AngularJS the difference is that it is client side Routing. Here you specify the Fragment Identified identified by #. The difference in using Fragment Identifier is it the Web Application is not making a round trip to the server which is an essential concept in Single Page Application.


A Module can have Config. Config in turn have Route.
In the previous example we hard coded Controller into View.

$routeProvider Service

The $routeProvider service is used to define a route.

AngularJS Seed

Instead of  manually creating the structure for AngularJS project we can make use of AngularJS Seed. AngularJS Seed will create the necessary routes, views, scripts, etc. for you.



Here I am adding AngularJS Seed to an empty Web Application Project.





App.js

App.js is present inside js folder.

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
  config(['$routeProvider', function($routeProvider) {
      $routeProvider
          .when('/view1', {
          template: '/partials/partial1.html',
          controller: MyCtrl1});
      $routeProvider
          .when('/view2', {
              template: '/partials/partial2.html',
              controller: MyCtrl2
          });
      $routeProvider
          .otherwise({ redirectTo: '/view1' });
  }]);


$routeProvider is having a when function which expects a Fragment Identifier, template, controller.

Template is a View or a piece of html functionality. Here when you access view1 fragment you will be accessing partial1.html template.



_LayoutAngular.cshtml

<!doctype html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="/css/app.css"/>
</head>
<body>
  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>

  @RenderBody()
  
  <div>Angular seed app: v<span app-version></span></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>


Inside _LayouAngular.cshtml layout there are Urls.

ng-view

ng-view is the AngularJS equivalent of RenderBody in MVC or ContentPlaceHolder in Web
Forms.

Index.cshtml
@{
    Layout = "~/Views/Shared/_LayoutAngular.cshtml";
}
<h3>Shalvin P D - Index</h3>

<ng-view></ng-view>


Index.cshtml present inside Views/Angular is having the ng-view directive. Here the template will get injected.


No comments:

Post a Comment