AngularJS

AngularJS + RequireJS Example

Posted on Updated on

Prerequisite Dependency Javascripts Path –

You can download dependencies script files from below path.

Project Structure:-

 

 

 

 

 

 

 

 

index.html

HTML page for the arithmetic operation.

 

app.js

This is requireJS configuration file, so we defined all dependencies and javascript path.


requirejs.config({
	baseUrl: './scripts',
    shim : {
        angular: {
            exports : 'angular'
           },
        app:{
            deps:['angular','jquery']
        }

    },
    paths: {
        "angular" : "./../lib/angular.min",
        "bootstrap" :  "/../lib/bootstrap.min",
        "jquery":"./../lib/jquery-3.2.1.min",
        "main":"./../main"  
    }
});

requirejs(['main']);

main.js

In this file, we can add all components of AngularJS like Services, Controllers, Directive and Utility files. Since we are only using Controller file in this example so only Controller file is getting added into angular.module(…).


define(['RegisterControllers','angular'],function (RegisterControllers,angular) {

  angular.module('myApp', ['ui.controllers']);
  angular.bootstrap(document, ['myApp']);

});

Controllers/PrimaryController.js

In this Controller file, methods are defined which handle action on button clicked.


define(['angular'],
	function (angular) {

		var myCtrl = null;
		PrimaryController = function($scope){
			this.$scope = $scope;
			this.$scope.myCtrl = this;		
			this.init();
		}
		PrimaryController.$inject=["$scope"];

		PrimaryController.prototype ={
			init : function(){
        	this.$scope.message = "Hellow How are you";
        },
           doAction : function(){
           	var num1 = this.$scope.number1;
			var num2 = this.$scope.number2;

			this.$scope.result = parseInt(num1) + parseInt(num2);
           }
        
        };

		return PrimaryController;

	});

RegisterController.js –

Here, we register a Controller into angular.module(“ui.controllers”,[]). Also you can pass multiple controllers file path seperated by comma and assign into variables in function body then add all of them one by one in angular.module(…).controller(…).controller(..).

 


define(['./controllers/PrimaryController','angular'],
	function (PrimaryController,angular) {

    return angular.module("ui.controllers",[])
    	.controller("PrimaryController",PrimaryController);
});

Finally open index.html page in your browser, we will see the below output.

Download complete code here.

Thanks!!

Advertisements

$routeProvider vs $stateProvider in AngularJs

Posted on Updated on

angularjs$routeProvider vs $stateProvider in AngularJs

See overview and differences between $routeProvider and $stateProvide routing modules. Each module has some cons and pros are given below.

$routeProvider  :-

It exposes APIs that allow you to define routes for your application. It works on specifics URLs to a Controller and assign a Template page. Generally, template page is rendered inside <ng-view> elements on parent page. We can embed URLs in two way –  ng-href or href attribute.

Html code below :- 

<ul class="nav navbar-nav">
     <li><a href ng-href="/home">Home</a></li>
     <li><a href ng-href="/contact">Contact</a></li>
</ul>

Below are basic $routeProvider Implementation snippet :-

routeProvider-1
limitation:-

  • The Page can contain only one ng-view on Page.
  • $routeProvider don’t know about Parent/Child relationship.

It’s simple and easier to use.

$stateProvider:-

It works similar to $routeProvider but it purely focus on state rather than URLs. We can leverage lot of feature by using UI-Route provides:-

  • You can have multiple ui-view on single page
  • Various view can be nested in each other and maintain by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Other way you could relative routing using only @ to change ui-view="some", This will replace the ui-view rather than checking it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

Doing this, you have to download angular-route-ui.js file.

Below have some Html code that defined different routing and routing scope like child and parent relationship.

<ul class=”nav navbar-nav”>
<li><a ui-sref=”home“>Home</a></li>
<li><a ui-sref=”home.listOfBook“>Books</a></li>
<li><a ui-sref=”home.login“>Login</a></li>
<li><a ui-sref=”about“>About Us</a></li>
</ul>

In about html page having two named section “columnOne” and “columnTwo” and each section has a Controller and View template attached in angular config( see Javascript ) to render the output inside respective     <ui-view> area.

aboutPage.html

stateProvider-html

Below are basic $stateProvider Implementation snippet :-

stateProvider-1

 

ref :

https://github.com/angular-ui/ui-router/wiki
https://docs.angularjs.org/tutorial/step_07
Thanks !!!

 

AngularJS Bootstrap Model + ngAnimate with Login Example

Posted on

angularjs

This is another AngularJS with Bootstrap Login example, In this article we covered animation, broadcasting and AngularJS directive.

In the below example demonstration, we will see how to implement Bootstrap Model in AngularJS having some animation effects. In the Home page there is a Login option at right side that will  trigger on onClick event and displayed a popup Login Model Form. We applied some validation like  minLength=4 and required on Login Form elements. Once the Form Login validation is done then it send to Controller to process and authenticate “username” & “password” using some backend service.  Here we don’t implement any backend service ( will disuss in next article ) for authentication but we simply pull out user information from Login window and broadcast to another controller ( baseController) that user is authencated so Login option on navigator bar to be changed to User Info drop down.

During the transition of Model window we applied simple effects ( fade in& out) on Model but you can get lots of transition effects on internet and you can do apply.

Also we created a Directive for “FormElement” which is of course replacement of redundent html code.

Require Javascripts :-

https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js
http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js
http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.0.2.js
<link href=”http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css&#8221; rel=”stylesheet”>

here we have created a simple html page, containing a navigation bar at top. A Login Option is given in right side of nav bar.

Render Html page below:-

formModel-output1

Login Model Html :-

formModel-login

Angular Javascript :-

formModel-JS

 

Simple animation CSS :-

formModel-css

When Login is clicked on nav bar then a Login Popup window will be rendered. Initially Submit button is diable. It get enabled only if all validation get true.
formModel-output3

Next, when User enter valid “username” and “password”  and click on Login button then  Home page will be rendered with some User information and Logout button in drop down section. see in next screen-

 

formModel-output5

 

 

 

 

 

formModel-output4

Please find complete code here.
Thanks !!

AngularJS Form Validation with Bootstrap

Posted on Updated on

angularjs

 

 

 

In this article, we will see Angular Validation with bootstrap Framework, Angular provide some build-in validtion that make earier to do lots of stuff in client side. In below example we create a simple User Form that take some input from Client and validate using some angular ( custom directive validation ) and bootstrap validation together.

Although, AngularJS validation works on HTML 5 validation.

Custom Validation using Directive :-

Here, we create a directive i.e ngCompare that compare on Cofirm Password field with “password” field if these two fields are matched then it’s allow to proceed to form submition otherwise error message will be displayed either inline or prompt msg.

Create a Directive i.e ngCompare that compare two fields ( password with comfirm password)

angular-userForm-directive

 

Angular Validation properties  here :-

  1. $valid : It is a boolean property that tells whether the form or it’s inputs are valid or not. If all containing form and controls are valid, then it will be true, otherwise it will be false.
  2. $invalid : It is a boolean property that tells whether the form or it’s inputs are invalid or not. If at least one containing form and control is invalid then it will be true, otherwise it will be false.
  3. $dirty : It is a boolean property that is actually just reverse of pristine i.e. it tells whether the form or it’s inputs are modified by the user or not. If the form or it’s inputs are modified by the user, then it will be true, otherwise it will be false.
  4. $touch : the control has been blurred
  5. $error :This is an object hash which contains references to all invalid controls or forms. It has all errors as keys: where keys are validation tokens (such as required, url or email) and values are arrays of controls or forms that are invalid with given error. For a control, If a validation fails then it will be true, otherwise it will be false.
  6. $pristine:– It is a boolean property that tells whether the form or it’s inputs are unmodified by the user or not. If the form or it’s inputs are unmodified by the user, then it will be true, otherwise it will be false.

Angular Form Methods  :-

  1. $addControl() : This method registers a control with the form.
  2. $removeControl() :This method remove a control from the form.
  3. $setDirty() : This method set the form to Dirty state.
  4. $setValidity() : This method set the validity of a form control.
  5. $setPristine() : This method set the form to its pristine state.

angular-userForm

How Validation work here :-

Displaying error message when validation get failed.

angular-userForm-output-error

 

Once Validation compated, ready for Form submition :-

angular-userForm-output

See complete code here.

Angular Directive Examples

Posted on Updated on

angularjs

What is Angular Directive?

It’s used to customized the functionality of HTML DOM element ( such as an attribute, element name, comment or CSS class ). Using Angular Directive we can create  own or customized the behavior of DOM elements.

Please read more about it here 

Before going to example section, let have a look on directive options:-

  • restrict :-
    • 'A' – only matches attribute name
    • 'E' – only matches element name
    • 'C' – only matches class name
    • 'AEC' – matches either attribute or element or class name
  • template :- HTML template inline
  • templateUrl :- URL of HTML template.
  • link :- Manipulate the DOM element.

Example 1 : “say-hello” Directive 

angular-example1

Output :- 

angular-example1-output

Example 2 : “myDirectiveAtts Directive 

This directive attribute simply bind DOM event and apply CSS on Div element.

angular-example2

Example 3 : “fileModel Directive for File Upload :

angular-example3

angular-example3-output
Render Page

Thanks !!

 

Inventory Example with AngularJS

Posted on Updated on

angularjs

 

 

 

 

Another AngularJS sample example of inventory system which give you better glance about single page application development, we do not use any validation in this example, will covert in next topics.

Better you download it and run on your system.

 

inventory-angular

This method ( ‘AddInCart’) gets called when use enter ‘Add in Cart’ button, extract ng-model values one by one and calculate total price as per item selected price multiply by quantity.
In the next line, create a JSON object with key and value and insert into array  ‘cartItems‘.

$scope.AddInCart = function() {
 var itemName = $scope.item.name;
 var itemPrice = parseInt($scope.item.price);
 var itemQty = parseInt($scope.qty);
 var totalPrice = parseInt(itemPrice * itemQty);
 var jsonCartItem = {
 'name' : itemName,
 'price' : itemPrice,
 'qty' : itemQty,
 'totAmt' : totalPrice
 };
 $scope.cartItems.push(jsonCartItem);
 }

This method gets called when user wanted to remove item from cart. Javascript method “splice” is used to add or remove the element from array.

 $scope.removeCartItem = function(index){
 $scope.cartItems.splice(index,1);
 }

This method called inline whenever a new Items has been added or deleted into Cart Array then this method fired.

 $scope.subTotalAmt = function(){
 var cartItemsLength = $scope.cartItems.length;
 var totAmt =0.0;
 if(cartItemsLength>0){
   for(var i=cartItemsLength-1;i>=0;i--){
      totAmt += parseInt($scope.cartItems[i].totAmt);
   }
 }
 return totAmt;
 }

Complete code below :-

<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js
</head>
<body ng-controller="myController">
 
 <h1>Welcome to Inventory Example with AngularJS</h1>
<table border='1'>
 <tr>
 <td colspan='2'>
 <h2>Select Items</h2>
 </td>
 </tr>
 <tr>
 <td>Items</td>
 <td><select ng-model="item"
 ng-options="item.name for item in items"
 ng-change="getPriceList(item);" readonly>
 </select></td>
 </tr>
 <tr>
 <td>Price</td>
 <td><input type="test" ng-model="item.price" readonly></td>
 </tr>
 <tr>
 <td>Qty</td>
 <td><select ng-model="qty" ng-options="q for q in itemQty" readonly>

 </select></td>
 </tr>
 <tr>
 <td colspan="2"><input type="button" ng-click="AddInCart()"
 value="Add in Cart">
 </tr>
 </table>
 
 <h2>Cart Items</h2>
 
<table style="width:60%;">
 <thead>
 <tr>
 <th>Name</th>
 <th>Price per Unit</th>
 <th>Quantity</th>
 <th>Total Amount</th>
 <th>Remove Item</th>
 </tr>
 </thead>
 <tbody>
 <tr ng-repeat="cart in cartItems">
 <td>{{cart.name}}</td>
 <td>{{cart.price}}</td>
 <td>{{cart.qty}}</td>
 <td>{{cart.totAmt}}</td>
 <th><a href ng-click="removeCartItem($index)"><span class="glyphicon glyphicon-remove-circle"></a></span>
 </tr>
 <tr class="panel panel-info">
 <th colspan="3" align="right">Total Amt:</th>
 <th colspan="2">{{subTotalAmt()}}</th>
 <tr>
 </tbody>
 </table>
</body>
// Javascript start here 
 
 var dashboard = angular.module("dashboard", []);

 dashboard.controller('myController', function($scope) {
 $scope.items = [ {
 'name' : 'Computer',
 'price' : 20000
 }, {
 'name' : 'RAM',
 'price' : 2000
 }, {
 'name' : 'CPU',
 'price' : 10000
 }, {
 'name' : 'Mouse',
 'price' : 200
 }, {
 'name' : 'Keyboard',
 'price' : 500
 } ];
 $scope.itemQty = [ 1, 2, 3, 4, 5, 6 ];
 $scope.cartItems = [];

 $scope.getPriceList = function(item) {
 $scope.item.price = item.price;
 }

 $scope.AddInCart = function() {
 var itemName = $scope.item.name;
 var itemPrice = parseInt($scope.item.price);
 var itemQty = parseInt($scope.qty);
 var totalPrice = parseInt(itemPrice * itemQty);
 var jsonCartItem = {
 'name' : itemName,
 'price' : itemPrice,
 'qty' : itemQty,
 'totAmt' : totalPrice
 };
 $scope.cartItems.push(jsonCartItem);

 }
 $scope.removeCartItem = function(index){
 $scope.cartItems.splice(index,1);
 }
 
 $scope.subTotalAmt = function(){
 var cartItemsLength = $scope.cartItems.length;
 var totAmt =0.0;
 if(cartItemsLength>0){
   for(var i=cartItemsLength-1;i>=0;i--){
      totAmt += parseInt($scope.cartItems[i].totAmt);
   }
 }
 return totAmt;
 }
 });
 
// Javascript end here with  tag
</html>
 

Please find complete code from google drive :- https://drive.google.com/file/d/0B8SgSioNRbwcNERQdll3VEwycFk/view?usp=sharing

Arithmetic Operation Using AngularJS

Posted on Updated on

angularjs

Another simple example to calculate Arithmetic operation like +,-,*,/,% operator between two operands.


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS Example2</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Select Operator</td>
<td><select ng-model="operation"
ng-options="item for item in operations">
</select></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {

$scope.operations = [ '+', '-', '*', '/', '%' ];
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;
switch ($scope.operation) {
case '+':
$scope.result = parseInt(num1) + parseInt(num2);
break;
case '-':
$scope.result = parseInt(num1) - parseInt(num2);
break;
case '*':
$scope.result = parseInt(num1) * parseInt(num2);
break;
case '/':
$scope.result = parseInt(num1) / parseInt(num2);
break;
case '%':
$scope.result = parseInt(num1) % parseInt(num2);
break;
default:
$scope.message = "Invalid Selection ";
break;

}
};

});
</script>

</html>

Output here :-

angular-exm-002