My studying notebook

2014/07/15

AngularJs, RequireJs, Grunt and Bower Part4 - How to extend your own code with ASP.NET MVC

7/15/2014 04:33:00 PM Posted by Unknown , , , , , , , 9 comments

This article is part of a series of posts on RequireJs, AnguarJs, Grunt and Bower. Here are the parts so far:

  1. AngularJs, RequireJs, Grunt and Bower Part1 - Getting Started and concept with ASP.NET MVC
  2. AngularJs, RequireJs, Grunt and Bower Part2 - Grunt
  3. AngularJs, RequireJs, Grunt and Bower Part3 - generator-angular-requirejs-grunt-bower with ASP.NET MVC
  4. AngularJs, RequireJs, Grunt and Bower Part4 - How to extend your own code with ASP.NET MVC
  5. AngularJs, RequireJs, Grunt and Bower Part5 - generator-angular-requirejs-grunt-bower with Express.js //to be done

In previou aticles that we talked about how to integrate AngularJs, Requirejs, Grunt and bower with ASP.NET MVC. If you don’t want to create those file structure manual. You can install generator-angular-requirejs-grunt-bower yeoman generator.

Simple step to install yeoman generator

  • install generator: npm install -g generator-angular-requirejs-grunt-bower
  • cd to project root folder
  • execute command yo angular-requirejs-grunt-bower

Scenario

As basic concept we mentioned that we want to treat ControllerName/actionName as single page application and try to reuse shared code as possible base on this file structure. Now, let’s create a new ASP.NET MVC controller and extend new AngularJs application.

Step 1: create new ASP.NET MVC controller

  1. please create a new controller named ProjectController via Visual studio.
  2. Add new view named Index.cshtml
  3. modify Views/Project/Index.cshtml. The only thing you need to do is add Angular route directive ng-view. We will handle UI in AngularJs partile view.
@{
    ViewBag.Title = "Product";
}

<div ng-view></div>

Step 2: create new AngularJs application

create file structure as following.

  1. Public/js/views/Project, AngularJs application container and named same as Controller
  2. Public/js/views/Project/index.js, application entry point
  3. Public/js/views/Project/patials, we will put all partials view HTML here
  4. Public/js/views/Project/patials/project-index.html, default AngulaJs route view.
  5. Public/js/controllers/product-controller.js, Product controller.
project-index.html: Product partials view
<div>
    this is Project Index page.
</div>
product-controller.js: Product controller
define(['controllers/controllers'], function (controllers) {
    controllers.controller('ProjectIndexCtrl', ['$scope',
        function ($scope) {
            console.log('ProjectIndexCtrl execute.');
        }
    ]);
});

index.js: Product AngularJs single page application entry point.

'use strict';

require([
        'angular',
        'app',
        'domReady',
        'controllers/product-controller',
        'bootstrap'
],
    function (angular, app, domReady) {
        var root = require.toUrl('.').split('.')[0];
        app.config([
            '$routeProvider', '$httpProvider', '$sceDelegateProvider', '$locationProvider',
            function ($routeProvider, $httpProvider, $sceDelegateProvider, $locationProvider) {
                // sec
                $sceDelegateProvider.resourceUrlWhitelist(['self', '.*']);

                // route
                $routeProvider.
                when('/', {
                    templateUrl: '/public/js/views/Product/partials/product-index.html',
                    controller: 'ProjectIndexCtrl',
                    resolve: {}
                }).
                otherwise({
                    redirectTo: '/'
                });
            }
        ]).run([
            '$rootScope',
            function ($rootScope) {
                // global variable

                $rootScope.$safeApply = function ($scope, fn) {
                    $scope = $scope || $rootScope;
                    fn = fn || function () { };
                    if ($scope.$$phase) {
                        fn();
                    } else {
                        $scope.$apply(fn);
                    }
                };
            }
        ]).constant('$', $);

        domReady(function () {
            angular.bootstrap(document.body, ['myAngularApp']);

            $('html').addClass('ng-app: myAngularApp');
        });
    }
);

Preview

Product

Step 3: Let’s extend shared service for different single page application

Till now, we have two AngularJs single page application HomeController and ProductController and they don’t include any AngularJs service, directive or filter module.

  • Add a new ASP.NET MVC BookController ApiController
  • Add a AngularJs server named /Public/js/services/bookService.js. Using ng-source to call API
  • Inject book-service.js to Product application
  • Inject book-service.js to Home application

Add BookController ApiController

// GET: api/Book
public IEnumerable<string> Get()
{
    return new string[] { "ABookApart.CSS3.For.Web.Designers.2010", "AngularJS Directives" };
}

book-service.js

Add a new AngularJs service locate in Public/js/service/book-service.js.

define(['services/services'], function (services) {
    // Book resource
    services.factory('BOOK', ['$resource', function ($resource) {
        var resetUrl = '/api/Book';
        var resource = $resource(resetUrl, {}, { get: { method: 'GET', isArray: true } });

        return resource;
    }]);

    // BookLoader
    services.factory('BookLoader', ['$q', 'BOOK', function ($q, BOOK) {
        return function () {
            var delay = $q.defer();
            BOOK.get(function (data) {
                delay.resolve(data);
            }, function (error) {
                delay.reject('Unable to fetch Book list');
            });
            return delay.promise;
        };
    }]);
});

Inject book-service.js BookLoader to AngularJs route resolve

If you are familier with AngularJs. There is a resolve function you can call in AngularJs route. We define a BookLoader function that implement with promise pattern. Then, we can inject the result to our controller. Resolve can help us to fetch API before controller called.

How can we inject book service to AngularJs application via RequireJs require feature. That’s mean we can inject different feature in other application easily.

js/views/Product/index.js

....
'controllers/product-controller',
'services/book-service',
...

controller/Product-controller.js

controllers.controller('ProjectIndexCtrl', ['$scope', 'books', function ($scope, books) {
    console.log('ProjectIndexCtrl execute.');

    $scope.books = books;
}]);

Preview
preview

Inject book-service.js BOOK service to AngularJs route resolve

We have defined BOOK AngularJs service. Different with Product application. We use BOOK service instead of BooKloader promise service.

// js/views/Home/index.js
...
'domReady',
'controllers/home-controller',
'services/book-service',
'bootstrap'
...
// js/controller/home-controller.js
define(['controllers/controllers'], function (controllers) {
    controllers.controller('HomeCtrl', ['$scope', 'BOOK', function ($scope, BOOK) {
            console.log('HomeCtrl execute.');

            $scope.books = BOOK.get({}, function (books) {
                return books;
            });
    }]);
});

We inject BOOK service in controller directly and bind Book.get() to $scope.books. Whatever we use AngularJs route resolve or inject service directly. They points to same service we defined.

Preview
Preview

Grunt

As we mentioned before. we still can build for every AngularJs we defined. Befere we build our application, we need to modify Gruntfile.js manual.

...
 modules: [{
        name: 'views/Home/index'
    }, {
        name: 'views/Product/index'
    }],
...    
grunt 

Github Source Code

cage1016/AngularJsRequireJsGruntBower

After you clone source code from github repo, you can run following command:

  • git checkout -f step-0 is status project created
  • git checkout -f step-1 is status Nuget install Require.js.
  • git checkout -f step-2 is status project Add AngularJs, RequireJs, Grunt and Bower to Public folder.
  • git checkout -f step-3 is status modify _Layout.chtml to render RequireJs. You will see the final result.
    • Please cd to AngularJsRequireJsGruntBower\AngularJsRequireJsGruntBower\Public and execute bower install to restore those library project included.
  • git checkout -f setp-4 is status ready to do grunt tasks.
    • Please cd to AngularJsRequireJsGruntBower\AngularJsRequireJsGruntBower\Public and execute npm install to restore grunt required libraries.
    • execute command grunt to do grunt tasks.
  • git checkout -f step-5 extend Product application
  • git checkout -f step-6 extend AngularJs service book-service and add BookLoader to route resolve
  • git checkout -f step-7 extend AngularJs service book-service and inject BOOK service to controller
  • git checkout -f step-8 add Product to Gruntfile.js module block

9 comments:

  1. Thanks for sharing this valuable information to our vision. You have posted
    a trust worthy blog keep sharing.
    Angularjs Training In Hyderabad

    ReplyDelete
  2. Hi, I am not clear that how can i add grunt.js and how the files get bundled
    from Barun

    ReplyDelete
  3. This blog is really very well interesting as well as i got more more information from your blog so please update latest information.


    Best Dental Clinic In Vellore

    ReplyDelete
  4. your blog is really great and you have shared about the impressive information of different languages, so please say about those things too.

    Digital Marketing Company in Chennai

    ReplyDelete
  5. hello sir,
    thanks for giving that type of information.Business visa provider

    ReplyDelete
  6. To learn about Tropika Club's Search Directory for Beauty and Wellness Services, please visit Tropika Club now. 123movies

    ReplyDelete
  7. I was surfing the net and luckily I came across this site and found some very interesting things here. It's a lot of fun to read. I really enjoyed it. Thank you for sharing this wonderful information.

    Business Analytics Course in Durgapur

    ReplyDelete