2014年11月4日 星期二

ASP.NET MVC With AngularJS

 @Scripts.Render("~/bundles/angularjs")   要放在 angular.module使用之前

使用 controller的寫法

1.2
 function HelloController($scope) {
     $scope.greeting = { text: 'Hello' };
 }

1.3
var myApp = angular.module('myApp', []);

     myApp.controller('HelloController', ['$scope', function ($scope) {
         $scope.greeting = { text: 'Hello' };
     } ]);


or 

 function HelloController($scope) {
         $scope.greeting = { text: 'Hello' };
  }

// The $inject property of every controller (and pretty much every other type of object in Angular) needs to be a string array equal to the controllers arguments, only as strings
HelloController.$inject = ['$scope'];

 var myApp = angular.module('myApp', []);
 myApp.controller('HelloController', HelloController);


SPA 注意事項
1.要設定 SPA要先加入 angular-route.min.js

 //AngularJS
 bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
                        "~/Scripts/angular.min.js"
                       , "~/Scripts/angular-route.min.js"
                     
                        ));

2.設定連結
   a href="/#/routeOne"

   如果 default網頁是 Index.cshtml,可以寫成如上的連結,但如果不是,比如有一個網頁叫 SPATest.cshtml放在 Home目錄底下的話,連結修改如下:
 
   a href="/Home/SPATest/#/routeOne"

3.加上一個   <div ng-view></div>在你的 Index.cshtml (SPA的首頁)上

4.設定 angulasjs route,可儲存在 javascript檔
 
     //routing for angularjs
     var configFunction = function ($routeProvider) {
         $routeProvider.
        when('/routeOne', {
            templateUrl: '/RoutesDemo/one'
        })
        .when('/routeTwo', {
            templateUrl: '/RoutesDemo/two'
        })
       .when('/routeThree', {
            templateUrl: '/RoutesDemo/three'
        });

     }
     configFunction.$inject = ['$routeProvider'];

     myApp.config(configFunction);

5. 建立 contorller
     public class RoutesDemoController : Controller
    {
        //
        // GET: /RouttesDemo/

        public ActionResult One()
        {
            ViewBag.test = 1;
            return PartialView("SPAPartialTest");
        }

        public ActionResult Two(int donuts = 1)
        {
            ViewBag.Donuts = donuts;
            ViewBag.test = 1;
            return PartialView("Two");
        }
        public ActionResult Three()
        {
            ViewBag.test = 3;
            return PartialView("SPAPartialTest");
        }

    }

6.建立 partialview


Hands On Lab: Build a Single Page Application (SPA) with ASP.NET Web API and Angular.js

Using AngularJs, ASP.NET MVC, Web API and EntityFramework to build NLayered Single Page Web Applications

【AngularJs + ASP.NET MVC】使用AntularJs快速建立ASP.NET MVC SPA網站

Getting started with AngularJS and ASP.NET MVC - Part One
Getting started with AngularJS and ASP.NET MVC - Part Two

AngularJS 開發 ASP.NET MVC

What's the difference between “return View()” and “return PartialView()”

沒有留言:

張貼留言