Wednesday, July 8, 2015

Adding Application Constants by removing Magic Strings in Angular applications

Defining App


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

Adding Constants


These constants are used to remove magic string from the application and user application level constants,

myApp.constant('AppConstants', (function () {
    var constants = {};
 
    constants.App = {};
    constants.App.Name = "My Application Name";
 
    constants.LocalStorage = {};
    constants.LocalStorage.profileKey = "profile";
    constants.LocalStorage.clientsKey = "clients";
 
 
    constants.clsProfile = {};
    constants.clsProfile.Email = "Email";
 
    return constants;
 
}())
 
);

How to add toaster in Angular JS

Index page:

 Open Home main (Container page) page  and add following references.
Remember, If you will add following lines in any of angular view, it will not work.

Reference:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/0.4.9/toaster.min.css" rel="stylesheet" />
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js"></script>


Add Toaster Tag

<toaster-container></toaster-container>

Tuesday, July 7, 2015

Angular JS $state.go redirects to home page

Topic


$urlRouterProvider.otherwise() called before $state.go()

Explaination

i faced above problem in one of my application. I needed to change the state on click event of anchor tag. User was being navigated to Otherwise route rather than redirecting to the route that was called on click event. following was my code,



<a ng-click="SetClient(Name)" href="#">{{Name}}</a>

function SetClient(stateName)
{
$state.go(stateName);
}

The following configuration is used for redirection if any other url is provided.
$urlRouterProvider.otherwise("/home");

The Problem

When ever i clicked on the hyperlink, it redirected to home state rather than the state name that was passed to SetClient.

Solution

I found out that "#" hash sign is creating problem. i removed hash sign and it worked fine.
<a ng-click="SetClient(Name)" href>{{Name}}</a>
Hash sign was calling "$urlRouterProvider.otherwise".