Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Localization of AngularJS Applications

Introduction 

Localization and internationalization is common requirement of large organizations to create website or web application that is available in multiple countries.

What is Localization?

Localization is the adaptation of a product or service (i.e. website, web application) to meet the needs of a particular language, culture or desired population's "look-and-feel”.

Angular Localization

You can use Localization module for your angular app to add localization feature in your application for multiple languages. 

Localizable pluralization is supported via the ngPluralize directive.Additionally, you can use MessageFormat extensions to $interpolate for localizable pluralization and gender support in all interpolations via the ngMessageFormat module.

All localizable Angular components depend on locale-specific rule sets managed by the $localeservice.

Following are steps some steps required to add localization in your application,

1. You have to download libraries and include them in the project.
2. Then provide translation files and set them working.
3.  In this step change angular $locale after the language change.

Simple example

Add three views one for home page another two for English US and German language.

1. Create main view named "Home.html" and other two views(english and german) named "index.html" under en_us/de_de folder.

 


2. Add angular js file.

3. Add AngularJS English localization file in english view.

4. Add AngularJS German localization file in german view.

5. Add AngularJS model and controller code.


Home View

<!DOCTYPE html>
<html>
<body>
    <div ng-app="mainApp" ng-controller="myLocalizationController">
        <h3>Select the localization:</h3>
        <a href="en_us/">English (USA)</a><br />
        <a href="de_de/">German (Germany)</a>
    </div>
</body>
</html>

 

English View

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="../Content/js/angular.min.js"></script>
    <script src="../Content/js/angular-locale_en-us.js"></script>
    <script src="../Content/js/LocalizationController.js"></script>
    <title>English Employee Data</title>
</head>
<body>
    <div ng-app="mainApp" ng-controller="myLocalizationController">
        User Name:{{Employee.Name | uppercase}}
        <!--date -->
        Birth Date:{{Employee.BirthDate | date:'medium' }}
        <!--number -->
        Package:{{Employee.Package | number }}
        <!--currency -->
        <p>Payment: {{Employee.Payment | currency}}</p>
    </div>
</body>
</html>

German View

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="../Content/js/angular.min.js"></script>
    <script src="../Content/js/angular-locale_de-de.js"></script>
    <script src="../Content/js/LocalScript.js"></script>
    <title>German Employee Data</title>
</head>
<body ng-app="mainApp">
    <div ng-controller="myLocalizationController">
        User Name:{{Employee.Name | uppercase}}
        <!--date -->
        Birth Date:{{Employee.BirthDate | date:'medium' }}
        <!--number -->
        Package:{{Employee.Package | number }}
        <!--currency -->
        <p>Payment: {{Employee.Payment | currency}}</p>
    </div>
</body>
</html>

AngularJS Controller and Model Code

angular.module("mainApp", ["ngLocale"])
  .controller("myLocalizationController"function ($scope, $locale) {
      // Store the current locale ID in a variable
      $scope.localeId = $locale.id;
 
      // Store the current date/time in a variable
      $scope.currentDate = new Date();
 
      $scope.Employee = {
          id: 1,
          Name: 'Shourya Kendre',
          BirthDate: dateOut,
          Package: 52503.30,
          Payment: 700
 
      };
  });

 धन्यवाद मित्रानोआपला प्रत्येक दिवस आनंदी आणि सुखी जावो  

REST Web Service with AngularJS

In this post I will cover with example how to create a JSON based WCF Rest Web Service and use this with angular web application.

Rest Web Service

RESTful Web Services are web services that follws REST architecture. In REST Architecture everything is a resource.

Following are core advantages using rest web services

Light weight
Scalable
Maintainable

Example:

In this example with the assumption that REST based service is already in place to retrieve the doctors and add doctor’s data, we will write the angular application using this WCF web service.

Angular Service created using Factory

var DoctorService = angular.module('DoctorService', [])
DoctorService.factory('DoctorsDataOp', ['$http', function ($http) {
 
    var urlBase = 'http://localhost:54393/Service1.svc';
    var DoctorDataOp = {};
 
    DoctorDataOp.getDoctors = function () {
        return $http.get(urlBase + '/GetallDoctors');
    };
 
    DoctorDataOp.addDoctors = function (doct) {
        return $http.post(urlBase + '/AddDoctors', doct);
    };
    return DoctorDataOp;
 
}]);

 

There are two methods first method “getDoctors” retrieves all doctors data using the $http.get and Second method add doctors using the $http.post. In the service we are using other inbuilt angular service $http to make the call to the service.

 

Angular Controller

var myApp = angular.module('myDoctorApp', ['DoctorService']);
 
myApp.controller('DoctorController', function ($scope, DoctorDataOp) {
    $scope.status;
    $scope.doctors;
    getDoctors();
 
    function getDoctors() {
        DoctorDataOp.getDoctors()
            .success(function (dcts) {
                $scope.doctors = dcts;
            })
            .error(function (error) {
                $scope.status = 'Unable to load doctors data: ' + error.message;
            });
    }
 
    $scope.addDoctor = function () {
 
        var doct = {
            ID: 1,
            Name: $scope.Name,
            Phone: $scope.Phone,
            Address: $scope.Address
        };
        DoctorDataOp.addDoctor(doct)
            .success(function () {
                $scope.status = 'Inserted Doctor Suceessfully!';
                $scope.doctors.push(doct);
            }).
            error(function (error) {
                $scope.status = 'Unable to insert Doctor: ' + error.message;
            });
    };
});

 

In the controller we are using “getDoctors” and “addDoctors” functions to scope. As it is clear from the name that these functions are used to fetch doctors and add doctors data respectively. As a dependency DoctorSevice module is passed in the module and in the controller we are passing the DoctorDataOp service as the dependency.

 

Angular View

In following view there are two sections first section used add new doctors data and second section simply displays doctors data using ng-repeat directive.

In the input form we are setting Name, Phone and Address properties on the $scope object and then calling addDoctor () function of the controller to add a doctors data to the database.

<html>
<head>
    <title></title>
     <script src="~/Content/js/angular.min.js"></script>
    <script src="Content/js/AngularRestService.js"></script>
    <script src="Content/js/DoctorController.js"></script>
</head>
<body>
    <div ng-app="myDoctorApp" ng-controller="DoctorController">
            <form class="well">              
                <input type="text" name="name" ng-model="Name" placeholder="doctor name" /> <br/>      
                <input type="text" name="phone" ng-model="Phone" placeholder="doctor phone" /> 
                 <input type="text" name="address" ng-model="Address" placeholder="doctor address" />           
                <br /><br/>              
                <input type="button" value="add doctor" ng-click="addDoctor()" />
            </form>
            <br/>
            <table class="table">
                <tr ng-repeat="d in doctors">
                    <td>{{ d.Name }}</td>
                    <td>{{ d.Phone }}</td>
                    <td>{{ d.Address }}</td>
                </tr>
            </table>
        </div>
</body>
</html>

धन्यवाद मित्रानो !! Thanks Friends !!


ASP.NET MVC with AngularJS

AngularJS with ASP.NET MVC 

I have already shared post on AngularJS with asp.net CRUD operations but in this post I am going to share Basic example that retrieves data from database and display it using AngularJS,Asp.net MVC and Entity framework.

AngularJS

AngularJS is a JavaScript framework open-source client-side web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Following are some angular directives I used in this example

ng-app

Declares the root element of an AngularJS application, under which directives can be used to declare bindings and define behavior.

ng-controller

Specifies a JavaScript controller class that evaluates HTML expressions.

ng-repeat

Instantiate an element once per item from a collection.

AngularJS with ASP.NET MVC Example

In layout section I added reference to angularJS controller,service code.

Layout:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="~/Content/js/AngApp.js"></script>
    <script src="~/Content/js/Employee.js"></script>
    <script src="~/Content/js/Service.js"></script>
</head>
<body>
    @RenderBody()
 
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Asp.net MVC View and AngularJS View

 @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
 <div ng-app="EmpApp" ng-controller="EmpCntrlr">
        <table border="1" cellpadding="10" align="center" class="table table-bordered table-striped">
            <tr>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Name'">
 
                <td>
                    {{emp.Id}}
                </td>
                <td>
                    {{emp.Name}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                 {{emp.EmailId}}
                </td>
            </tr>
        </table>        
         </div>

 

Asp.net Entity framework and Model

 

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace AngularMvcApp.Models
{
    public class EmolyeeDbContext : DbContext  {
        public EmolyeeDbContext(): base("DefaultConnection")      { }
   protected override void OnModelCreating(DbModelBuilder modelBuilder)      {         Database.SetInitializer<EmolyeeDbContext>(null);    }
        public DbSet<EmployeeData> EmployeeData { get; set; }
    }
}

 

Asp.net Employee Model

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; 
 
namespace AngularMvcApp.Models
{
public class EmployeeData
    {
        [Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }  }
}

 

Asp.net MVC Controller

using AngularMvcApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            return View();
        }
        // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmolyeeDbContext contextObj = new EmolyeeDbContext())
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

 

AngularJS Model

var app = angular.module("EmpApp", []);

AngularJS Controller

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
});

AngularJS Service

app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
});

धन्यवाद !!!