Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Sunday, 11 March 2018

AngularJS Routing Using UI-Router

Background

In the last post, we saw AngularJS Hello World example. In this post, we will see how we can create an angular JS app with routing using UI-Router module. If you have not read the previous post I would highly recommend you read that first.


 Setup

There is a small change in the file structure than our previous example. Create files as shown in the following screenshot -



Following are file details -
  • helloWorld.html : Our main HTML file. Starting page similar to the last example.
  • helloworld.module.js : Declares angular module and it's dependencies
  • helloWorld.controller.js : Controller for the module
  • helloworld.config.js : Config for the module.  
  • login.html : login page to route to
  • setting.html : setting page to route to
 Also make sure you install http-server module to host your angular app and test it -
  • npm install -g http-server


Then you can simply run in your project directory as -
  • http-server -o 
NOTE : -o option is to open browser.

AngularJS Routing Using UI-Router


Now let's see one by one content of each file. Let's start with  helloWorld.html -

<html>
    <head>
        <title>Hello World!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
            <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
            <script type="text/javascript" src="helloworld.module.js"></script>
        <script type="text/javascript" src="helloWorld.controller.js"></script>
        <script type="text/javascript" src="helloworld.config.js"></script>
    </head>
    <body ng-app="helloWorldApp">
        <div ng-controller="helloWorldAppController" ng-init="init()">
                  <p>Enter Message here : <input type="text" ng-model="message"></p>
                   <p>Entered Message :  {{ message }}!</p>

                   <a href="/login">Login</a> <br/>
                   <a href="/setting">Setting</a>

                <div class="content-wrapper">
                    <ui-view></ui-view>
                </div>    
        </div>
    </body>
</html>


In this base HTML file we have just referenced other angular JS files that we need. An interesting thing to note here is the ui-view tag. This is where the injected code goes. But we will see that in a moment.


Let's see out module and controller files next -


helloworld.module.js

(function() {
    'use strict';
    console.log("In hello world module");
    angular.module('helloWorldApp', ['ui.router']);
})();


This code just declares your module as we did in last example. Only change is that it has an additional dependency on ui.router module. Note we have included a new script in helloWorld.html to get code for this module.


helloWorld.controller.js

(function(){
    'use strict';
    console.log("In hello world controller");
    angular.module("helloWorldApp").controller("helloWorldAppController", function($scope) {
        $scope.init = function() {
            console.log("Init method called");
            $scope.message = "Hello World!";
        }
    });

})();


This is a controller of the module we defined. This is again same as we did in last post. No new changes here.


Now let's see our new logic - helloworld.config.js


(function() {
    'use strict';
    console.log("In hello world config");
    angular.module('helloWorldApp').config([
        '$stateProvider',
        '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
            $stateProvider.state('login',{
                     url: "/login",
                     templateUrl: "login.html"
                })
            .state('settings',{
                    url: "/setting",
                    templateUrl: "setting.html"
            });
        }
    ]);
})();






 

This is actually the routing logic. For eg. if it encounters URL "/login" it will render page "login.html" that we have in same folder. Same for setting.html.


Finally, let's see out login.html and setting.html files -


login.html -


<h1>This is a login page!</h1>
<a href="/helloWorld.html">Back</a>



setting.html -


<h1>This is a login page!</h1>
<a href="/helloWorld.html">Back</a>


 Once you have all files in place just run http-server as follows -




And you should see following behavior - 


 






But wait what happened? I thought the code was supposed to be injected at tag ui-view.

This is because we do not actually use angular routing per say to change the state. Let's do some changes to see how we can do that. Change your login href as follows - 

<a href="" ng-click="replaceLoginPage()">Login</a>


and now add this method to the controller -


(function(){
    'use strict';
    console.log("In hello world controller");
    angular.module("helloWorldApp").controller("helloWorldAppController", function($scope, $state) {
        $scope.init = function() {
            console.log("Init method called");
            $scope.message = "Hello World!";
        }

        $scope.replaceLoginPage = function() {
            console.log("In replaceLoginPage");
            $state.go("login");
        }
    });

})();



And now it should replace ui-view tag.









Related Links



Tuesday, 27 February 2018

AngularJS Hello World Example

Background

AngularJS is a client-side javascript framework developed by Google which can interact with HTML. It helps to easily create and maintain SPA (Single page applications)

Some of its features are -
  1. Helps create responsive applications
  2. Provides MVC capabilities
  3. Dependency injection
  4. Powerful and flexible with less code to write
NOTE: AngularJS is a very old framework. The first version is called AngularJS. Later versions are just called angular. You can see the detailed release history - https://github.com/angular/angular.js/releases. This post will try to explain a simple Hello World program in Angular JS. This is mainly for projects that are already on it. If you are starting a new project I would highly recommend to go with later angular versions. You can visit https://angular.io/  for the same.


 AngularJS Hello World Example

Let's start by writing our HTML file. Create a folder where you can store your code files. Now in this folder create two files -
  1. helloWorld.html
  2. helloWorld.js
And add following content to it -

helloWorld.html:

 <html>
    <head>
        <title>Hello World!</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>       
        <script type="text/javascript" src="helloWorld.js"></script>
    </head>
    <body ng-app="helloWorldApp">

        <div ng-controller="helloWorldAppController" ng-init="init()">
                  <p>Enter Message here : <input type="text" ng-model="message"></p>
                   <p>Entered Message :  {{ message }}!</p>
        </div>

    </body>
</html>



helloWorld.js  :

 (function(){
    'use strict';
    console.log("In JS");
    var helloWorldApp = angular.module("helloWorldApp", []);
    helloWorldApp.controller("helloWorldAppController", function($scope) {
        $scope.init = function() {
            console.log("Init method called");
            $scope.message = "Hello World!";
        }
    });

})();



Now you can simply open the helloWorld.html file and see the changes. 

 

Understanding the code

Now that we saw the behavior let's try to understand the code.

In our code we have initialized a angular module using ng-app directive. In the javascript we get this module using andular.module() function.  Inside a module you can have multiple controllers controlling various parts of your html. In our case we have defined a controller called helloWorldAppController that controls the div element we have defined. In the javascript we are getting this controller from our module.


Once you have the controller you can define varibles and functions that you can access in the HTML controller by this particular controller. You can also notice the variable called "message" that is defined in the controller is accessible in the HTML using {{message}} syntax. You would also see the binding exist using the ng-model syntax. This is called two way binding. So value changed in the input field is immediately visible in same HTML using {{message}} syntax as well as the controller using $scope.message. In the html where we have declared controller we have also specified init method using ng-init and you can see this menthod defined in controller using $scope.init. This is called when controller is initialized and this function in the controller script initialized messages variable to "Hello World!" that is reflected in HTML page.



Lastly we have injected our controller script (helloWorld.js ) and  angular js script in the html for our angular js code to work. Make sure angular script is the 1st one added.

All keywords starting with ng- are angular directived.
  • ng-app
  • ng-controller
  • ng-init
  • ng-model 

t> UA-39527780-1 back to top