This article is part of a series of posts on RequireJs, AnguarJs, Grunt and Bower. Here are the parts so far:
- AngularJs, RequireJs, Grunt and Bower Part1 - Getting Started and concept with ASP.NET MVC
- AngularJs, RequireJs, Grunt and Bower Part2 - Grunt
- AngularJs, RequireJs, Grunt and Bower Part3 - generator-angular-requirejs-grunt-bower with ASP.NET MVC
- AngularJs, RequireJs, Grunt and Bower Part4 - How to extend your own code with ASP.NET MVC
- 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
- please create a new
controller
namedProjectController
via Visual studio. - Add new view named
Index.cshtml
- modify
Views/Project/Index.cshtml
. The only thing you need to do is add Angular route directiveng-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.
Public/js/views/Project
, AngularJs application container and named same asController
Public/js/views/Project/index.js
, application entry pointPublic/js/views/Project/patials
, we will put all partials view HTML herePublic/js/views/Project/patials/project-index.html
, default AngulaJs route view.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
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
. Usingng-source
to callAPI
- Inject
book-service.js
toProduct
application - Inject
book-service.js
toHome
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;
}]);
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.
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 createdgit 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 executebower install
to restore those library project included.
- Please cd to
git checkout -f setp-4
is status ready to do grunt tasks.
- Please cd to
AngularJsRequireJsGruntBower\AngularJsRequireJsGruntBower\Public
and executenpm install
to restoregrunt
required libraries. - execute command
grunt
to do grunt tasks.
- Please cd to
git checkout -f step-5
extendProduct
applicationgit checkout -f step-6
extend AngularJs servicebook-service
and addBookLoader
to route resolvegit checkout -f step-7
extend AngularJs servicebook-service
and injectBOOK
service to controllergit checkout -f step-8
addProduct
toGruntfile.js
module block
Thanks for sharing this valuable information to our vision. You have posted
ReplyDeletea trust worthy blog keep sharing.
Angularjs Training In Hyderabad
Great Article android based projects
DeleteJava Training in Chennai
Project Center in Chennai
Java Training in Chennai
projects for cse
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
Hi, I am not clear that how can i add grunt.js and how the files get bundled
ReplyDeletefrom Barun
Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.
ReplyDeleteDigital Marketing Company in Chennnai
This blog is really very well interesting as well as i got more more information from your blog so please update latest information.
ReplyDeleteBest Dental Clinic In Vellore
your blog is really great and you have shared about the impressive information of different languages, so please say about those things too.
ReplyDeleteDigital Marketing Company in Chennai
I read your articles very excellent and the i agree our all points because all is very good information provided this through in the post.
ReplyDeleteDigital Marketing Company in Chennai
I read your articles very excellent and the i agree our all points because all is very good information provided this through in the post.
ReplyDeleteDigital Marketing Company in Chennai
It is very helpful for me. Keep blogging like this.
ReplyDeleteHealthcare Analytics Company
Finance Analytics Company
Telecom Analytics Company
Retail Analytics Company
Analytics Company
US IT Staffing Agency
It is very useful thank you for sharing Angularjs Online Training Hyderabad
ReplyDelete
ReplyDeleteThanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
Restaurant in OMR
Apartments in OMR
Villas in OMR
Resorts in OMR
hello sir,
ReplyDeletethanks for giving that type of information.Business visa provider
All the latest updates from the Python Automationminds team. Python Automationminds lets you program in Python, in your browser. No need to install any software, just start coding straight away. There's a fully-functional web-based console and a programmer's text-editor
ReplyDeletePhyton training in Chennai
Nice one, I guess we just need to stop for a brief moment and read through. I dont read that much but I really had some good time grabbing some knowledge. Still I am out to speak and propose you exotic stuffs like
ReplyDeleteexotic carts official
buy exotic carts
buy exotic carts online.
exotic carts review
exotic carts website
gorilla glue exotic carts.
exotic carts fake
kingpen official
kingpen review.
mario carts official
mario carts online
exotic carts website
exoticcartsofficial
exotic carts for sale
exotic carts thc
exotic cartridges
exotic carts flavors
@exoticcartsofficial
real exotic carts
exotic carts vape cartridges
exotic cart
exotic carts vape pen
mario kart cartridge
king pen battery
exoticcarts
exotic carts official website
supreme cartridges
mario carts cartridges
exotic carts review
710 kingpen gelato
710 king pen battery
supreme cartridge
supreme brand oil cartridge
what are exotic carts
what are pre rolls
pre rolls
Buy Fake Euros online.
ReplyDeleteFor more information, Contact us via:
Email: counterfeitnotesonline@gmail.com
Whatsapp number:+1 (480)269-2191
Webside: www.counterfeitnotesonline.com
Web Link: https://www.counterfeitnotesonline.com
Page links:
Buy Fake Euros online
https://www.counterfeitnotesonline.com/2019/12/09/buy-fake-euros-online/
To learn about Tropika Club's Search Directory for Beauty and Wellness Services, please visit Tropika Club now. 123movies
ReplyDeleteNice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
ReplyDeleteCyber Security Course in Bangalore
Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
ReplyDeleteCyber Security Training in Bangalore
All of pitbull dog and puppy are sent home. Current on shots, deworming, flea treated, health certificate, genetic health guarantee, and AKC registration papers. All new families are required to sign a contract that includes a basic health guarantee and a 3 year genetic health guarantee.
ReplyDeletePitbull Puppies For Sale
american pitbull terrier puppies
pitbull puppies for sale near me
pitbull breeders for sale
pit bull breeders near me
pit bull puppy
baby pitbulls for sale
All of pitbull dog and puppy are sent home. Current on shots, deworming, flea treated, health certificate, genetic health guarantee, and AKC registration papers. All new families are required to sign a contract that includes a basic health guarantee and a 3 year genetic health guarantee.
ReplyDeletePitbull Puppies For Sale
american pitbull terrier puppies
pitbull puppies for sale near me
pitbull breeders for sale
pit bull breeders near me
pit bull puppy
baby pitbulls for sale
All of pitbull dog and puppy are sent home. Current on shots, deworming, flea treated, health certificate, genetic health guarantee, and AKC registration papers. All new families are required to sign a contract that includes a basic health guarantee and a 3 year genetic health guarantee.
ReplyDeletePitbull Puppies For Sale
american pitbull terrier puppies
pitbull puppies for sale near me
pitbull breeders for sale
pit bull breeders near me
pit bull puppy
baby pitbulls for sale
buy dmt online buy lsd online buy weed online buy hydrocodone gun shop buy counterfeits
ReplyDeletebuy Rottweiler puppies online
ReplyDeletebuy munchkin kittens online
buy british shorthair kittens
buy antminer online
buy dmt online
buy French bulldog puppies
Your site is truly cool and this is an extraordinary moving article and If it's not too much trouble share more like that. Thank You..
ReplyDeleteDigital Marketing Course in Hyderabad
Thank a lot. You have done excellent job. I enjoyed your blog . Nice efforts
ReplyDeleteData Science Certification in Hyderabad
Wow, happy to see this awesome post. I hope this think help any newbie for their awesome work and by the way thanks for share this awesomeness, i thought this was a pretty interesting read when it comes to this topic. Thank you..
ReplyDeleteArtificial Intelligence Course
I need to thank you for this very good read and i have bookmarked to check out new things from your post. Thank you very much for sharing such a useful article and will definitely saved and revisit your site.
ReplyDeleteData Science Course
Excellent Blog! I would like to thank you for the efforts you have made in writing this post. Gained lots of knowledge.
ReplyDeleteData Analytics Course
Awesome article. I enjoyed reading your articles. this can be really a good scan for me. wanting forward to reading new articles. maintain the nice work!
ReplyDeleteData Science Courses in Bangalore
I am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
ReplyDeleteBusiness Analytics Course in Bangalore
What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
ReplyDeleteAI Courses in Bangalore
I bookmarked your website because this site contains valuable information. I am very satisfied with the quality and the presentation of the articles. Thank you so much for saving great things. I am very grateful for this site.
ReplyDeleteData Science Training in Bangalore
I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...
ReplyDeleteDigital Marketing Training in Bangalore
I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.
ReplyDeleteArtificial Intelligence Training in Bangalore
Truly incredible blog found to be very impressive due to which the learners who go through it will try to explore themselves with the content to develop the skills to an extreme level. Eventually, thanking the blogger to come up with such phenomenal content. Hope you arrive with similar content in the future as well.
ReplyDeleteMachine Learning Course in Bangalore
Thanks Your post is so cool and this is an extraordinary moving article and If it's not too much trouble share more like that.
ReplyDeleteDigital Marketing Course in Hyderabad
You have done excellent job Thanks a lot and I enjoyed your blog. Great Post.
ReplyDeleteData Science Certification in Hyderabad
I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
ReplyDeleteData Analytics Course
What an incredible message this is. Truly one of the best posts I have ever seen in my life. Wow, keep it up.
ReplyDeleteAI Courses in Bangalore
Great post happy to see this. I thought this was a pretty interesting read when it comes to this topic Information. Thanks..
ReplyDeleteArtificial Intelligence Course
I am really enjoying reading your well written articles. I am looking forward to reading new articles. Keep up the good work.
ReplyDeleteData Science Courses in Bangalore
ReplyDeleteI am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
Business Analytics Course in Bangalore
Nice Post thank you very much for sharing such a useful information and will definitely saved and revisit your site and i have bookmarked to check out new things frm your post.
ReplyDeleteData Science Course
A good blog always contains new and exciting information, and reading it I feel like this blog really has all of these qualities that make it a blog.
ReplyDeleteArtificial Intelligence Training in Bangalore
It is late to find this act. At least one should be familiar with the fact that such events exist. I agree with your blog and will come back to inspect it further in the future, so keep your performance going.
ReplyDeleteDigital Marketing Training in Bangalore
I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.
ReplyDeleteData Science Training in Bangalore
I have read your article, it is very informative and useful to me, I admire the valuable information you offer in your articles. Thanks for posting it ...
ReplyDeleteCloud Computing Institutes in Bangalore
I really enjoyed reading this post and keep up the good work and let me know when you can post more articles or where I can find out more on the topic.
ReplyDeleteData Science Online Course
I recently came across your article and want to express my admiration for your writing skills and your ability to get readers to read from start to finish.
ReplyDeleteAWS Course in Hyderabad
Really impressed! Information shared was very helpful Your website is very valuable. Thanks for sharing.
ReplyDeleteBusiness Analytics Course in Bangalore
Good blog and absolutely exceptional. You can do a lot better, but I still say it's perfect. Keep doing your best.
ReplyDeleteData Science Training in Nagpur
A good blog always contains new and exciting information and as I read it I felt that this blog really has all of these qualities that make a blog.
ReplyDeleteData Analytics Course in Patna
Good blog and absolutely exceptional. You can do a lot better, but I still say it's perfect. Keep doing your best.
ReplyDeleteData Science Training in Durgapur
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.
ReplyDeleteBusiness Analytics Course in Durgapur