AngularJS with RequireJS example for Developers

AngularJS with RequireJS example

AngularJS is a framework for creating dynamic web applications. It supports dynamic binding for data manipulation and lets you create templates by using directives, form validations, routing and Dependency Injection.

RequireJS : Most of the large scale web applications use a number of JavaScript files which are included using tag. Sometimes one script is dependent on another script and sometimes scripts may have compatibility issues with the browser.
To avoid these kind of issues, we can use RequireJS module loader framework, which works well for almost all supported browsers. Today we will setup our code environment to work with AngularJS and RequireJS.

I will show you step by step process with code, how you can use RequireJS with AngularJS.

Before we start, it is very import to understand the directory structure of the application. As shown below



Now I will start describing the steps to create application with angular and require. When we are using RequireJS for module loading, we need to configure RequireJS first.

We can configure require with the help of the function require.config .

paths: you can provide module location and it’s corresponding module name.
shim: you can provide module dependency.
deps: will load the required module when application starts.
priority: you can set important module which should load first before any other module for example JQuery should load first.

main.js
'use strict';

require.config({
    waitSeconds: 200,
 //paths to the library
 paths: {
  'jQuery' : '../lib/jquery/jquery-3.1.1.min',
  'angular' : '../lib/angular/angular',
  'angular-resource' : '../lib/angular/angular-resource',
  'angular-ui-router' : '../lib/angular/angular-ui-router',
  'domReady' : '../lib/domready/domready',
  'bootStrap' : '../lib/bootstrap/js/bootstrap.min'
 },

 //modules and dependencies
 shim: {
  'angular-ui-router': {
   'exports': 'angular-ui-router',
   deps: ['angular']
  },
        'angular': {
            'exports': 'angular',
            deps: ['jQuery']
        },
        'jQuery': {
            'exports': 'jQuery'
        },
        'angular-resource': {
         'exports': 'angular-resource',
         deps: ['angular']
        },
        'domReady': {
         'exports': 'domReady',
         deps: ['angular']
        },
        'bootStrap': {
         'exports': 'bootStrap',
         deps: ['jQuery']
        },
        'customJs': {
         'exports': 'customJs',
         deps: ['jQuery']
        }
 },

 //kick start application
 deps: [
  './PostMyAds/Homepage/postMyAdsHomepage',
  './app/bootstrap.js'
 ],

 priority: [
     "angular"
 ]
});
After RequireJS configuration, we need to configure AngularJS so that we can use it in the web application. First we need to provide module name for AnuglarJS application which will be used in whole application.

We can define module name as :

angular.module(‘Module Name’, [dependent modules, dependency injection]);

Use define in order to define modules which can be used by other parts of your application.

app.js
'use strict';

define(['angular','jQuery','angular-resource','angular-ui-router'], function(angular) {
    var app = angular.module('app', ['ngResource','ui.router']);

    app.run(['$http','$rootScope',
       function($http, $rootScope) {

        }
    ])

    .config(function ($provide, $urlRouterProvider, $locationProvider, $httpProvider) {
                $httpProvider.defaults.withCredentials = true;
                $locationProvider.html5Mode(false);
                //$urlRouterProvider.otherwise('/SAR/');
       });

    return app;
});
After AngularJS configuration, it is time to bootstrap your application or initialize your AngularJS application. Angular.bootstrap lets you manually start your application, which gives you more control over your application like how to initialize modules and events before your application starts.

For example in our case we are using domReady, our modules will not execute until it is safe to interact with DOM.

bootstrap.js
define([
    'require',
    'angular',
    'app'
], function (require, angular, app) {
    require(['domReady!'], function (document) {
        angular.bootstrap(document, ['app']);
    });
});
It’s done, our configuration part is completed for AngularJS and RequireJS. Now we will create the modules for the application. For that purpose, I have created separate directory (SAR) which will contain application modules like Homepage module.

PostMyAds/Homepage/postMyAdsHomepage.js

This file is the root of this module, this file will call it’s sub modules like config, controller and views. It is better to separate our modules on how they are functionally dependent with each other.
'use strict';

define([
     'app',
     './controllers/homepage',
     './config/homepage'
], function(app) {
 console.log('Home Page module loaded....');
});
Next module is configuration module for homepage.

app/PostMyAds/Homepage/config/homepage.js

In this module, we will provide state (routing) configuration of our homepage.

We can configure with $stateProvider.state function. $stateProvider.state, you can provide name to the state, url for that state, templateUrl html page to be called and you can provide controller as well.
'use strict';

define(['app'], function(app) {
 app.config(['$stateProvider', function($stateProvider) {

  $stateProvider
       .state('home', {
       url : '/',
       templateUrl : './app/PostMyAds/Homepage/views/homepage.html',
       controller : 'HomepageCtrl'
       });
 }]);
});
Next step is to create controller for the homepage. I did not add any functionality inside controller. app/PostMyAds/Homepage/controller/homepage.js
'use strict';

define(['app'], function(app) {
 app.controller('HomepageCtrl', ['$scope', '$rootScope',function($scope, $rootScope) { 

 }]);
 console.log("HomepageCtrl Controller loaded..");
});
You can also add service directory just like controller and config and add module to root module of the Homepage “postMyAdsHomepage.js” then you will be able to use service easily. index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="/PostMyAds/">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>AngularJS by Example</title>

  </head>
  <body>
<div ui-view></div>
<script data-main="app/main" src="lib/requirejs/require.js"></script>    

  </body>
</html>
That’s it, now your application is ready to run 🙂

One thought on “AngularJS with RequireJS example for Developers”

Leave a Reply

Your email address will not be published. Required fields are marked *