AngularJS Routes with $routeProvider and $stateProvider

AngularJS Routes are used to load different views or states depending on whether you use a ng-Route or ui-Route. The traditional way of linking the pages in your application is just fine, but with AngularJS routes you can handle dynamic binding better and the routes are easier to remember for the user.

Routing with Angular JS allows bookmarking the same url with different categories easier. Routes allow different views to load depending upon the url. Same route can be given to more than one view. For the user, only the keyword appears to be changed, even though the views are loading from different html pages. Basically AngularJS routes are two types:

  1. ngRoute: No nested routes are present
  2. ui.router: Nested routes are present

ng-Route

Include the angular-route js in the script file. You will also need a server for the routes to work. You can set up the Apache Tomcat server. We pass the ngRoute as a dependency to the module while defining an angular module.

var app =angular.module(‘myApp’, [‘ngRoute]);

Using the app.config service, we can define the different routes for the links. The keywords used are ‘when’ and ‘otherwise’. You can have any number of ‘when’ in a $routeProvider provided everytime you return a templateUrl and a controller for that route. For example, in your application you have two menu items, Login and Home. In that case, you have to have two route specified in your $routeProvider. Further, you have to create two additional html pages which have to load in those routes. Also, you have to create two controllers to define what happens in the html pages. Here is an example.

myApp.config(function($routeProvider){
$routeProvider.
       when(‘/home’,{
       templateUrl: ‘home.html’,
       controller: ‘HomeCtrl’
}).
      when(‘/login’,{
      templateUrl: ‘login.html’,
      controller: ‘LoginCtrl’
}).
      otherwise({
      redirectTo: ‘/login’
});
});

Remember to pass the $routeProvider to all the controllers as a function parameter.

myApp.controller(“HomeCtrl”, function($scope, $routeProvider){

});

In the index.html body you have to set up a container or placeholder for the views to load.  The a links are identified in the html with the ‘#’.

<a href=’#/login’>Login</a>|<a href=’#/home’>Home</a>

<div ng-view></div>

ui.router

Include the CDN of the ui.router javascript file in your index.html. ui.router uses a $stateProvider. We pass the ui.router as a dependency to the module while defining an angular module.

var demoapp = angular.module(“demoapp”, [‘ui.router’]);

In ui.router, all the routes are identified with a state rather than a ‘#’ Any number of child routes can be created using the $stateProvider. It uses application state changes to load the views accordingly.

The states are managed hierarchically. $stateProvider is defined inside the app.config service. It defines the different states and templateUrls to be loaded for the states. Each state can also defined along with the parent. Here, in this example, list is the child view of home.

demoapp.config(function($stateProvider){
    $stateProvider.state(‘home’, {
    state: ‘home’,
   url: ‘/home’,
   templateUrl: ‘home.html’,
   controller: ‘CarCtrl’
}),
   $stateProvider.state(‘login’, {
   state: ‘login’,
   url: ‘/login’,
   templateUrl: ‘login.html’,
   controller: ‘BarCtrl’
}),
   $stateProvider.state(‘list’, {
   state: ‘list’,
   url: ‘/list’,
   parent: ‘home’,
   templateUrl: ‘home.list.html’,
  controller: ‘ListCtrl’
});
});

In the child state, you have to specify the parent state. Remember to pass the state to all the controllers as a function parameter.

demoapp.controller(“BarCtrl”, function($scope, $state){

});

In the html, you have to refer to the states in the link. ‘ui-sref’ is used to link the states in the $stateProvider. ui-sref is the wrapper that supports the href in ui-routing. AngularJS will convert the state reference to a href automatically. Also, specify the ui-view to load the views in the container or placeholder.

<a ui-sref=”login”>Login</a>|<a ui-sref=”home”>Home</a><br>

<div ui-view></div>

Routing is pretty simple once you get a hang of it. Just implement and include the correct javascript files in the script tag.

AngularJS Directives

AngularJS directives are a cool way of defining behavior and using it any way you want. You can have a directive with your name and have it do any kind of work you want depending on the situation. AngularJS directives control your DOM behavior.

Directives

Directives guide the HTML compiler to control the elements so they can behave in a certain way. The rendering of HTML inside the AngularJS application is controlled by the directives. Depending on the type of directives, they can be used to change the behavior.  Think about it like the word ‘change’. You can use it to refer to ‘change of clothes’ or ‘spare change’. It depends on the context. Similarly, Directives too can be used to behave differently if used in different contexts.




Built-in Directives

Here are some key details about directives.

AngularJS has some crucial inbuilt directives which can make your application behave in a certain way. Directives can be integrated with the HTML or can be used in the Javascript.

One thing which is cool about directives is its naming. The naming of a directive follows camel case when used in Javascript: (ngApp). Whereas, if the directives are used in a HTML, the name is separated with a hyphen: (ng-app).

There are four basic directives:

  1. ng-app : To auto-bootstrap and initialize an AngularJS application
  2. ng-model : To bind between HTML control and application data
  3. ng-init : To initialize application data
  4. ng-view : To switch between different views

There are many builtin directives, here are my favorites:

  1. ng-controller : To attach a controller class to the view
  2. ng-bind : To replace the text of the element with value of an expression
  3. ng-repeat : To instantiate a template once per item from a collection
  4. ng-hide : To show or hide the given element based on given expression

Directives are defined in a similar way as the Controllers and services. They can be defined using app.directive method. The method takes a name of the directive and a function to define what happens in the directive.




Types of Directives

The four types of Directives are classified based on where they are applied. For example, let ‘kuul-stuff ‘ be the directive you wrote. Then,

  1. Attribute directives : The directive is used to change the attribute of an element                                                                                                            <span kuul-stuff=”expression”></span>
  2. Element directives: The directive itself is used as an element              <kuul-stuff></kuul-stuff>
  3. Class directives: The directive is used as a class                                       <span class=”kuul-stuff: exp;”></span>
  4. Comment directives: The directive is used in the comments section                <-directive: kuul-stuff exp ->

Custom Directives

Custom directives are a cool way of defining your own functionality or workflow. They enhance existing directives and are easy to integrate in the HTML. The custom directives are one of the super powers of AngularJS that makes it build powerful applications. Here are some details about custom directives.

Custom directives are defined using app.directive method. The directive function returns an object in its callback.

myapp.directive (‘myDirective’, function(){

—–     write your functionality—-

});

There are some options which must be specified while writing a directive.

  1. Restrict: Defines the type of directive<br>’A’ = Attribute directive, ‘E’ = Element directive, ‘C’ = Class directive, and ‘M’ = Comment directive. It is better to define Attribute or Element directive so you can determine what element a directive matches
  2. Template: Defines directive output content
  3. TemplateURL: Gives the path of the template to be shown
  4. Controller: Defines a controller in the directive which can be used to achieve a specific task.
  5. Controller As: Defines an alias for the controller so you can refer to the controller’s variables using the alias
  6. Scope: Defines the scope of the directive                                                            ‘false‘ = Default value, which means that the scope of the directive is shared by the scope of the parent. There is no local scope present    ‘true‘ = It means that a new scope is created for the directive. There is local scope present as well as we can access the parent scope.  ‘{}‘=Isolated scope means that there is no link between parent and directive scope. A new scope is created and cannot be accessed outside. Further, the directive cannot access the outside scope.                    It is suggested to have an isolated scope in large AngularJS applications to keep the data safe. However, isolated scope can be accessed outside using some techniques. There is some magic which will be revealed later. Okay, fine. Here is the key. Use the following property to achieve the given purpose.                                                                                                             ‘=’ = Handles two-way binding.                                                                     ‘@’=Passing string values to directives.                                                      ‘&’=External function invocation.
  7. Compile: Compile method is specified to achieve a function as soon as the page loads. It will return a link function. If the behavior occurs only once in the directive, use compile.
  8. Link: Link method is specified to achieve a function similar to compile but it loads after compile. If the behavior occurs multiple times in the directive, use Link.

The order the AngularJS guides the HTML compiler is:                                    Compile–>Controller–>Pre-link–>Link–>Post-link.                                             It depends on what you want to achieve in the directive.




Directive Example

Here is an example of a custom directive.

myapp.directive(‘kuulStuff’, function(){

return {

Restrict: A,

template: <span> Hey, I’m custom</span>,

templateUrl: ‘/kuulstuff/home.html’,

Scope: ‘true’,

Compile: function(telement,tattrs) {

console.log(“Hi, I’m custom”);

var linkfn=function($scope, element,attrs){

element.css(‘background-color, ‘red’);

}

return linkfn;

}),

controller: function(){

console.log(“In the controller”);

},

Link: function(scope, telement,tattrs){

console.log(“In the link”);

},

};

});

This is just ‘some’ information about directives in AngularJS. It may be a bit confusing in the beginning, but if you write more, you will be fine. Write your own directives and let me know how it goes. 🙂

AngularJS Controllers

AngularJS Controllers are where the most magic happens. Think that the controllers of an AngularJS application as the brain. The controllers are super smart and can define what happens on the (DOM) Document Object Model. AngularJS controllers along with the dependency injection form the super power of the AngularJS.

Controllers

Here are some key details AngularJS: How to Begin.

  •  Controllers are attached to the DOM through the ng-controller directive. When a controller is initialized, a javascript object will be created and all the functions in the .controller method can be accessed.
  • The initial state for the Angular $scope is available at the point where a controller is registered. All the properties of the $scope can be defined in the controller and can be accessed through the methods.
  • The .controller method can be used to add the controller’s constructor function to the module. Thus the constructor function is out of global scope.
  • Apart from the $scope, we can send additional parameters to the controller, such as services and functions. It is better to keep a controller as simple as possible. You can define as many controllers as you want in an AngularJS application.
  • A common practice of keeping controllers focused on the required logic is to define services and functions, which can in turn be passed to a controller through dependency injection.
  • Controllers can be nested and inherited. You have to note that the parent’s controller’s methods can be accessed in the child controller. And not vice versa.
  • Finally, remember that the controllers contain Javascript functions and are created by a standard Javascript object constructor and is bounded to a particular scope.

Example

Here is an example of how the Controller is initiated. You have to create an angular app called myapp. Also, you need to declare in the html to tell that it is an Angular application.

In the js:

myapp.controller(“MyCtrl”, function($scope){

$scope.message=”Hello”;

});

In the HTML or template:

<div ng-controller=”MyCtrl”>

{{message}}

<\div>

Your div is binded to the controller using the ‘ng-controller’ directive. The scope of the div is passed to the controller. The scope message variable’s value can be accessed in the div within the dual curly braces. Notice, how the name of the controller is defined with an ‘Ctrl’ and the double quotes used while defining and accessing the controller.

Similarly, you can have any number of controllers in your AngularJS application. You can have different Javascript files for each controller or just put it in one main file. This makes two way data binding easier and keeps your application simple!

AngularJS: How to Begin

AngularJS is the Javascript framework for website development. It is widely popular for the features including modularity and separation of concerns. Here are some of the keywords you must be familiar with in order to build web applications with AngularJS.

Steps to Create

Here are the steps to create an application with AngularJS:

  1. Download the latest angular js file from the Angular website. Or, you can include the CDN in the script tag of your web page
  2. Bootstrap the application with Angular by using ng-app
  3. Create a controller in the app
  4. Create the HTML view in the body
  5. Run the application in a web browser




Angular Keywords

  1. Directives: AngularJS uses the directives to convert static HTML into dynamic Document Object Model (DOM) with the help of special attributes such as:
    1. ng-app: To determine which part of the page will use Angular. It will load the respective module in that part.
    2. ng-controller: To identify which Javascript controller should be used in that part of the page.
    3. ng-model: To determine the binding between model and the input field ensuring two way binding.
  2. Modules: Modules ensure separation of concerns in manageable units. It can comprise all the directives, expressions, controllers, services, and filters. Modules specify how an application can be bootstrapped. Advantages of using modules are:
    1. Easy to declare and understand
    2. Code can be packaged as reusable chunks
    3. Easy to load in any order or load in parallel
    4. Faster unit tests because only relevant modules can be tested
    5. Modules can be used in end-to-end tests to override configuration
  3. Controllers: Controllers are defined by a JavaScript constructor function that is used to augment the Scope. They carry the business logic and determine how the view and model interact. The scope is a mandatory parameter that is passed to the controller.
    1. A controller is attached to the DOM via the ng-controller directive.
    2. Then,  Angular instantiates a new Controller object, using the specified Controller‘s constructor function.
    3. A new child scope will be created and made available as an injectable parameter to the Controller’s constructor function as $scope.
  4. Expressions: Expressions are Javascript code snippets that are placed in dual curly braces. {{ }}. They are used to load model directly into the view. Advantages of using expressions are:
    1. Evaluated in the current scope not in the global window
    2. Evaluation of errors is either null or undefined
    3. Loops, functions, exceptions cannot be handled in Angular expressions
    4. You need to create a controller for complex Javascript functions



  5. Scope: Scope is an object of the application model. It refers to the current context or boundary of the application. Scope establishes a connection between application controller and view. Some of the characteristics of the scope are:
    1. Used to observe model mutations
    2. Used to propagate events similar to DOM events
    3. Can be nested to limit the properties and behavior of application components
    4. A child scope can inherit from the parent scope
    5. Provide a context for expressions to evaluate

There are some other key terms such as filters, forms, routing, and services which are key to an Angular application.

Forget Everything: Just Learn AngularJS!

Angular or AngularJS is the next most powerful Javascript framework out there which is becoming increasingly popular among the tech world. Angular JS along with CSS frameworks such as Bootstrap coupled with the REST services is redefining Website development.

AngularJS

AngularJS was developed by Google and is the most important Javascript framework which makes easier for the developer to maintain the code and achieve the same and better functionality achieved with Javascript. The best part of AngularJS is that it is open source and is having the largest support available of all the frameworks available. The current stable version is 1.4.7 and Angular 2.0 is on the way!

Advantages of AngularJS

AngularJS is similar to Javascript and it can enhance the HTML which will enable it to achieve client side programming. It has inbuilt JQuery support called JQLite which helps us in utilizing almost eighty percent of functions in JQuery library.

Browsers

AngularJS has inbuilt multi-browser support and it works on any browser such as Chrome, Opera, Firefox, Safari, and Internet Explorer. You can access your website from any device, tablet, computer, or desktop. Large-scale Enterprise applications can be developed using AngularJS. AngularJS is widely used for developing Single Page Applications (SPA) which are super light and super fast at the same time delivering unbelievable amount of data to the user.

Design

AngularJS facilitates rapidly changing user requirements and business needs at the same time leveraging the skill sets of Front end web developers. Separation of concerns that is defining the model, view, and controller-makes it easier for modular programming and keeping any changes manageable. Dependency injection and use of patterns is simple with AngularJS. Angular supports the very popular Model View Controller pattern(MVC), Model View View Model (MVVM) pattern, and Model View Whatever (MVW) pattern. AngularJS also supports responsive design which is way more important for modern day websites.

Testing

AngularJS is also super good for testing as it allows testing of Model and Controllers in isolation. AngularJS is designed to run unit testing with Karma, Jasmine and Angular mocks. The interactions between View and other components requires mocking framework to unit test. This can be achieved with AngularJS.

Prerequisites

To learn AngularJS, you must be familiar with Javascript, HTML, CSS, and website development. You also need basics of Java, PHP, and MySQL. You can download the latest version from the Angular website or include the CDN in the script tag of your web page.