Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

Monday, January 19, 2015

AngularJS : On click redirect to another page

You may also like to see:

Besides the fact, AngularJs is Single Page Application, but we use URL routes for bookmarks and for better user experience. An application navigates around the different UI views for different features and actions. Since AngularJs is doesA it do not reload the complete page on each route change but it loads only the HTML for the current page and inject into our current page.

In AngularJs application if you want to redirect the application to another page of the application, and if your navigation element is an anchor tag then you can simply assign new route's URL to href attribute of the tag.

Dashboard

But if your element to navigate is not anchor tag then you need to write a scope function which redirects to your required page and you invoke this function on your element click.

  • Drafts

  • and define that function in controller as:

    $scope.redirectToDraftPage= function () {
       $location.path('/draft');
    };
    

    As you can see it is really annoying to write a scope function for each navigator items. So best way to achieve redirection in AngularJs on element click is to write a directive for this.

    Directives


    Directives are the custom tags and attributes, it is a way to extend HTML functionality. You can teach HTML new features using directive tags. AngularJs have many directives like ng-show, ng-app, ng-repeat, ng-class, ng-hide and many more.

    For more details on directive see this article.

    Directives are HTML tags and attributes. These are the way to use AngularJS extended HTML functionality. Using directives you can teach HTML new features by writing your own custom directives. AngularJS comes with a bunch of built-in directives like ng-app, ng-hide,ng-show, ng-repeat, ng-class and many others.

    Include a directive to your application, with restrict: 'A' defining that this directive is actually an extending Attribute, so whenever an element has this custom directive as attribute my defined functionality will be executed accordingly.

    So what this directive will do? It will assign a click event to that particular element which has this attribute. And it will redirect to the provided route onclick of the element.

    (function(){
    
        'use strict';
    
        function ngRedirectTo($window) {
            return {
                restrict: 'A',
                link: function(scope, element, attributes) {
                    element.bind('click', function (event) {
                        //assign ng-Redirect-To attribute value to location
                        $window.location.href = attributes.ngRedirectTo;
                    });
                }
            };
        }
        angular.module('app').directive('ngRedirectTo', ngRedirectTo);
        //inject $window service for redirection
        redirectTo.$inject = ['$window'];
    }());
    
    

    As naming convention for directive work as each camel-case word separated by hyphen( ie, - ). so our directive ngRedirectTo will be use in html as ng-Redirect-To. Here is the html:

     Dashboard 
    

    So now you include this directive to your index page and you can reuse this in your whole application wherever you want to navigate. Just add this attribute to the element and assign the route to it.

    If you have any feedback or suggestions or you want to add something to this article please post in comments.

    You may also like to see:

    Tuesday, May 6, 2014

    Learning AngularJS Part 4: Modular Design of AngularJS Application

    Here is Previous Part of this series:

    So here I am with the fourth article in the series of Learning AngularJS a guide for beginners. If you have not read the previous articles I recommend you to read in sequence, it will help you in understanding more quickly. In this post we will see the modularity of AngularJS Application.

    Before starting the real topic we need to see SPA (Single Page Application).

    So what is SPA?

    Single Page Application (SPA) or also called Single Page Interface (SPI) is a web application in which we have only one main view which is able to load many small pages on a fly, providing enhanced desktop application like fluid user experience.

    Traditional web application gives a blink and load impact when we route from one page to another while in SPA we load a main page on first time then we never post back completely instead we load partial or small HTML pages which make it faster and give it a better user experience.

    AngularJS application are Single Page Application, we have a main container page index.html load on first go then we only load the views which we required. To load the view at run-time we need to handle routing which is one of the main SPA concepts.

    In the previous post we see the directives, filters and data bindings, so now we will see AngularJS as a complete module and how controller, model views, directives, routes actually fit into this module.

    Module (AngularJS Application)


    we define module for our application as:


    <html ng-app="moduleName" > 
    

    and in JavaScript we create an object for our module as:

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

    Defining ng-app on html  tag will create a scope for angular application to the HTML and within this HTML scope angular directives , filters and data bindings will work. Since we are working on SPA application so having ng-app on html tag will scope whole application because when this page gets loaded then we not actually loading another page instead we loading partial views which get renders within this main page.

    Now we have define the module for our application now we need to add config, controllers, directive, services to our module. Module in actually a container in which we bundle all of our same functionality.

    Different module can also interact with each other. If you noticed the empty array passed to the module function with module name is the dependency injection we discussed in our first post. Here we can inject helping module or the module our application depends on. Like for route management we have many already written module available, we just need to pass the module object to our module and then we can use it within our application. We can define multiple modules:

    // Define sub modules with no dependencies
    angular.module('AccountApp', []);
    angular.module('LoginApp', []);
    
    // define main module and inject all other modules as dependencies
    angular.module('MainApp', [
        'AccountApp',
        'LoginApp']);
    

    Firstly we set config to our application module in which we can configure routing (we will see in details later). For this we just need to set config in module object.

    //we passed ngRoute is an external module for handling routing
    var moduleName = angular.module('moduleName', ['ngRoute']);
    
    moduleName.config(function ($routeProvider) {
      $routeProvider
    
       // route for the home page
       .when('/', {
        templateUrl: 'pages/home.html',
        controller: 'mainController'
      });
    
    }); 
    

    If you noticed here we also passed the controller to the view previously we declare the controller for a view within the view but that is not a recommended way as we said in Model View Controller view should be independent of controller so it must not be dependent on controller, so better way is to pass controller to view on the fly when we routing to view.

    Now View has the controller scope so it can access the scope variables of controller. We also need to add controller to our application module, for this we simple need to add controller to main module object.

     // create the controller and inject Angular's $scope
    moduleName.controller('mainController', function ($scope) {
        // create a message to display in our view
        $scope.message = 'Hello friend I am Main Controller';
    });
    
    and the view for home page will look like:

    <!-- home.html -->
    <div class="content">
            <h1>First Application</h1>
        <p>{{ message }}</p>
    </div>
    

    Here in this simple application we do not required a service or factory but in application when we interacting with APIs then we need to create factory [or services, provider, value]. These four are for same things with some different features. As we might need to get User data from server using AJAX calls and we may need it in five different controllers so instead of repeating the same code for fetching user's data in controllers we move this to User Service and then call this service from different controllers.

    We can define factory to our application using:

    moduleName.factory('MyService', function () {
    
        var factory = {};
    
        factory.getUser = function () {
            //..
        }
    
        return factory;
    });
    

    So lets review a complete cycle of angular application. Our application is a single module. It has configured routes when a particular URL get hit, it will be routed to specific View and Controller is also passed to the view at routing. Now View has the scope access of particular controller. It will call the controller for data. Controller will hit the service for data and service will send back data to controller fetching it from server. Controller pass that data to View and View render it accordingly.

    So It was concept of modularity in AngularJS application. If you have any confusions or feedback or If you want to see any particular topic regarding AngularJS in this series please comment below.

    Here is Previous Part of this series:
    Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,