Sunday, November 30, 2014

AngularJS : Dynamically Set Page Title

You may also like to see:


With AngularJS you create Single Page Application (SPA) which means you have only one page of your application and dynamically you change the content of that page. So it means that there is only one time rendering of your main Html after that you can switch or append the views without re-rendering.

As you have one page for your complete application, but you need the different page title property for each of your page. For example : home, about us, contact us, services etc. So you need a mechanism so your page title automatically get updated when you route to any page.

Lets see how can we achieve this with angularJs.

First thing you need to make sure for the implementation is that your ng-app="AppName" directive should be on html tag as title tag is in head section and to make it in application scope so you can update it within angularJS application you need to make it accessible from application.

<html ng-app="app">
   <head>
     Website Name
...


Now title tag is expecting title property in scope and since we need this common property in all of the controllers also title tag to be in that controller scope but instead of adding this property to all controllers we move this to rootScope and as rootScope is accessible from all over the application (under the ng-app="" scope) that's why we added ng-app directive to html tag.

Here in this code I am using Ui.Router which I found best and easiest for nested views and routing implementations.

Here we set the title property to all the routing object so now each route know the page's title property they are redirecting to.

//here we need to inject ui.router as we using it for routing
var myDemoApp = angular.module('myDemoApp', ['ui.router']);

//$stateprovider is the service procided by ui.router
myDemoApp.config(['$stateProvider', function ($stateProvider) {

//create route object
    
    var home= {
        url: '/home',
        templateUrl: 'views/Home.html',
        controller: 'HomeCtrl',
        title: 'home'
    },
    aboutUs= {
        url: '/aboutus',
        templateUrl: 'views/AboutUs.html',
        controller: 'AboutUsCtrl',
        title: 'About Us'
    },
    contactUs= {
        url: '/contactus',
        templateUrl: 'views/ContactUs.html',
        controller: 'ContactUsCtrl',
        title: 'Contact Us'
    };

//Now add these route state privider

    $stateProvider
       .state('home', home)
       .state('aboutus', aboutUs)
       .state('contactUs', contactUs);
}]);


Now each rout has attached the title property with, we need to access this property and set it in $rootScope so our title tag can have access on it.

Now we going to set this property form route configuration object to $rootScope service within each controller and for this we need to have access on state object in controller. Here we will use $state service of ui.router that will make state object available in controller.


angular.module('myApp')
    .controller('myController', ['$rootScope', '$state', function ($rootScope, $state) {

        //set property to rootscope
        $rootScope.title = $state.current.title;

}]);

Similarly each controller will set this property to $state.current.title or custom text which will be render in title tag.

Another easy way to achieve this is to assign it to rootScope on module run. This one time binding will set it to title property in rootScope and each route will update this accordingly.

Here is the code to set it on module run:

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    
     //set it here
     $rootScope.title = $state.current.title;
    
});

So this is the easy way to set your title property dynamically. If you have any question or feedback regarding this post please post in comments.

You may also like to see:

Friday, October 24, 2014

Checkbox checked Property

You may also like to see:


If you are working on web application have checkbox input on your page then you might need to check whether the checkbox is currently checked or not for applying some condition. There are many ways to check that is checkbox is checked or not.

Lets firstly see the pure JavaScript ways to check the property. In JavaScript after selecting the particular element you can easily check with checked property.

Lets see a demo, there is checkbox in your page with some unique Id i.e, myCheckBox  in following case.

<input type="checkbox" id="myCheckBox"/>
Now in JavaScript you firstly select the element and then get its checked property.
document.getElementById('myCheckBox').checked;
firstly we selected element by Id then we checked the property it will return true in case if check box is checked.

See here demo.

If you are working with jQuery and don't want to use pure JavaScript for this check then you have multiple ways to check this property:

using is(':checked')


You can use the function is() of jQuery to perform this action, what this function do is its check the selected element or set of elements for a condition you passed as argument and returns true if condition satisfied else false.

So to use is() firstly we need to select element than check for :checked selector which works for checkboxes, radio-buttons, and select elements.
$('#myCheckBox').is(':checked');

Here is demo

using prop()


Prior to jQuery 1.6  function attr() was used to get the property and attributes both according to element but it was confusing so after jQuery 1.6 new functio prop() was introduced to check the current property value of element.

Here firstly we need to know the difference between properties and attributes, Attributes are values we set in Html like we set the input textbox value to some initial text so you have set the attribute value but once page is loaded in browser and you changed the text of textbox. Here the difference will be visible on this moment attribute will still be the same you have provided in html while property will be updated with the updated value of textbox.

Here is textbox with attribute set with default text:
<input type="text" id="myTextBox" value='set attribute value' /> 
Now in jQuery try this:
console.log('Attribute Value is : '+$('#myTextBox').attr('value'));
console.log('Property Value is : '+$('#myTextBox').prop('value'));

Here is demo.

So lets say you have set checked attribute in html so on first time loading your checkbox get checked by default. So now attr() will always return the `checked` for $('#myCheckBox').attr('checked')  as it was provided in html(or updated later but not the current state). So you need to check it with prop() which will provide always the updated value.

Here is example using prop()
$('#myCheckBox').prop('checked');
Here is Demo which also show the fixed value provided by attr() if we set it in html.

using filter :checked

Another way to check the property is to use filter :checked in selector and then check for the length of elements. It is not recommended way and give you wrong output in case if you are working with class instead of id and there are more than one input radio button, checkbox or select elements on same page.
var isChecked = $('#myCheckBox:checked').length > 0;
Here is demo

So we have seen multiple ways of checking the checked property of checkbox. This is the thing which web developers usually have to use and cause of confusion in some scenario to select the correct way to use it.

Please give your feedback and suggestions for the articles in comments.

You may also like to see:

Thursday, September 11, 2014

JavaScript and Date Object

Here is Previous Part of this series:

Today I came to know an interesting case of Date object in JavaScript, I decided to share with my readers. DateTime object is always problematic for developers, specially in Web project where you need to handle different time zones.

JavaScript has the core class of Date, which has many useful date function. As JavaScript is client-side language and it runs on clients browser so it creates the Date object of clients local time-zone, so you don't need to handle localization for client but when you get this value on server than you need to change it to UTC (or as per business requirements). You can easily create current date-time object using:
var dateTimeNow = new Date();
or you can pass the date fields to constructor:
var dateTime = new Date(year, month, day, hours, minutes, seconds, milliseconds); 
Date class has many useful and handy function which allow you to manipulate Date object and perform different operations. You can get day, month, year, hour from date object or you can convert it to UTC date object. Similarly you can change day, month, year or time of an object.
var dt = new Date();
dt.setFullYear(2014); 
dt.setMonth(9);       
dt.setDate(11);   
One important thing in JavaScript Date object every developer should know is its month start from zero so:
dt.setMonth(0);   //set January
dt.setMonth(1);   //set February
dt.setMonth(2);   //set march
dt.setMonth(3);   //set April
dt.setMonth(4);   //set May
dt.setMonth(5);   //set June

So What will happen if you set 12 to this date object?

If you are thinking it will give you an error then you are wrong because it won't. What actually JavaScript date object will do is it will consider January of next year on setting the 12. So it sometime may cause error or unexpected result which might confuse developer if they are unaware of behavior.
var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(12);
dt.setDate(1);

alert(dt.toString()) //alert January 2015
Here is Demo

The inconsistent and confusing behavior I found for which I am writing this article is, setting Date to a date object.
If you set last date to a JavaScript date object in such a way that that date i.e, 31st for April, June, September, November or 30th ,31st for February. It will change the month.



For instance today is 20th of April 2014, and you coded to set 31st of October in way that you set the date first before changing month, Now if you are expecting Date object of 31st October than JavaScript is not your friend here as it will change the date object to October 1st 2014.

See code:
var dt = new Date(2014,3,20);  // 20th April 2014
dt.setDate(31);       //will change to 1st of May
dt.setMonth(9);       //1st October 2014

alert(dt.toString()) //alert 1st October 2014
Here is Demo

See it can be problematic and can cause a major defects if you ignored it. So always remember the following point in JavaScript Date object:
  1. If you are setting day of month than make sure to change month first than day.
  2. Remember month in JavaScript range from 0 to 11 (Jan - Dec)
  3. Be alert that JavaScript don't give error on setting month or date out from normal range.

Sunday, August 31, 2014

Object Oriented JavaScript : Inheritance, Polymorphism and Encapsulation

Here is Previous Parts of this series:

This is the third article of the series of Object Oriented JavaScript. In previous article we have seen private, public and static types of method.

Constructor


Lets start this article with Constructor as whenever you instantiate a class, you need to initialize some default values for this we initialize values in constructor but as in JavaScript Class is nothing but a function which contains methods and properties, so whenever you instantiate an object of JavaScript function /class it call that method so whatever you have initialize within the class will automatically be set. So you no need define separate constructor.
var Student = function () {
    console.log('Instance created');
    this.prop_one = "initialized value";
    this.prop_two = "initialized value";
};


var student = new Student();
console.log(student.prop_one); //initialized value
Here is Demo

Inheritance


Inheritance is one of the key feature of Object Oriented Programming, Inheritance can be achieved with prototype property. You can create a parent class and then inherit all the public methods and properties in child class. In JavaScript you do this by assigning an instance of the parent class to the child class. In ECMAScript 5 and above you can also use Object.create() to implement inheritance.

Lets see an example of inheritance in which we define a Human class and then inherit it in Student class and override some method of Human class.
// Define the Human constructor
function Human(fullName) {
  this.fullName = fullName;
}

// Add a couple of methods to Human.prototype
Human.prototype.speak = function(){
  alert("I speak English!");
};
Human.prototype.introduction = function(){
  alert("Hi, I am " + this.fullName);
};

See fiddle demo here.

Now we will create a child class of student

// Define the Student
function Student(fullName, school, courses) {

 //To initialize or call parent class constructor we need to Human.call()  
 //for call() we need to pass this instance
 //since fullName is Human class property inherited in student so we
 //passed it to parent class
  Human.call(this, fullName);

  // Initialize our Student properties
   this.school = school;
   this.courses = courses;
};

See fiddle demo here.

To inherit it from parent Human class we will set Student.prototype

//Do not try to set new Human() here as we are not calling it here
//calling Human here need to pass fullName property which is not available here
//the correct place to call parent object is in child class constructor
//as we call it in above Student function code
Student.prototype = Object.create(Human.prototype); // See note below

// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
As object.create() only works in browsers support ECMAScript 5 and above so to achieve this in older browser you can create your own function:
function createObject(prototype) {
    function emmptyClass() { }
    emmptyClass.prototype = prototype;
    return new emmptyClass();
}

Student.prototype = createObject(Human.prototype);
Lets see its usage:
// Example:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed"
student.speak();       // "I speak English!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See here the demo.

Polymorphism / Overriding


Polymorphism is the main pillar of Object Oriented Programming, it refers to the ability of an object to provide different behaviors in different state of objects. For example Parent class Human define a function of introduction() in which it contains simple introduction but Student object override it by adding more detailed information for introduction. So now Human() object has its own implementation of introduction and Student() has its own. It will be invoked according to the state of object.

As we inherited the Human object in Student object we can override its public methods by changing its definition.
// override the "introduction" method
Student.prototype.introduction= function(){
  alert("Hi, I am " + this.fullName + ". I am a student of " + this.school + ", I study "+ this.courses +".");
};
or you can also add new methods
// Add a "exams" method
Student.prototype.takeExams = function(){
  alert("This is my exams time!");
};

Here is usage of above overriden method:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed. I am a student of NED University, I study Computer Science."
student.speak();       // "I speak English!"
student.takeExams(); // "This is my exams time!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See demo here

Encapsulation


Encapsulation is the one of the three pillars (Encapsulation, Inheritance and polymorphism) of OOP, It is a way of structuring data and methods by concealing the implementation or internal logic of object. Like in above example Human object contains the speak() method which is available in Student object but Student object does not know about the implementation of speak() method. It is encapsulated in Human object/class, child class inherit it as it is and change the methods which is different from its parent.

Summary


In this series of article we see how beautiful and impressive JavaScript is. It is as powerful as any other Object Oriented programming language is. In above series of article I used the words like namespace, class for objects which actually do not exist in JavaScript, just to map the JavaScript to the language you are aware of it. Please write your feedback about this series of articles in comments.

You may also like to see:

Sunday, August 24, 2014

Object Oriented JavaScript : Classes, Methods and Properties

Here is Previous Part of this series:

This is second part of Object Oriented Programming in JavaScript. I would recommend to see previous article on Object Oriented JavaScript before continuing this.

JavaScript is classless, there is no class keyword in JavaScript but you can achieve same via objects.

In first part we see, how interesting JavaScript is. It allow us to work on familiar Object Oriented way of programming like we use in other programming languages. In first part we learn about namespaces, core classes, custom classes and class instances in JavaScript and there is complete article on Inheritance in JavaScript through prototyping.

In last article we see that in JavaScript class in nothing but a function. So writing a class in JavaScript is as easy as writing a function.

Public Methods & Properties


Here is a Student class with some public properties and function.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
var full_name = student.fullName()
console.log(full_name);
console.log('No. of Courses : ' + student.courses.length);
Here is JsFiddle Demo

Here in this example we used this keyword with function and properties to make it public. One thing which make JavaScript more powerful from any other OOP language is run-time changes in class structure. You can add new properties and function for any particular instance of function. So lets say in above example we add some more properties and function to an object:

var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
//runtime added property not present in class
student.middle_name = "H.";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
student.skills = function () {
return "Expert in JavaScript";
}

console.log(student.skills());

Here is JsFiddle Demo

One thing to notice in above example is that we have instantiate an object of Student class using statement var student = new Student() ; so the properties and function we adding to student object is only available to current object only. So if we created another object i.e, var student2 =new Student(); and try to call the skills() function with this it will throw an error.

 

Public Methods using Prototype


You can add public methods to a class using Prototype property then it will be available to all the instances of the class.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];
};

Student.prototype.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
Here is JsFiddle Demo

 

Private Method & Properties

 

In class methods and properties we remove this keyword and introduce var keyword (recommended by strict mode of ECMAScript) then it will be a private function and properties.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };
};

var student = new Student();
//will print undefine
console.log(student.private_property);
//this will throw an error private_function is not a function
console.log(student.private_function());

Here is JsFiddle Demo

Note here as we discussed above you can add new properties within object after creating an instance of class so here if you assign value to private_property it will create a new property in instance and assign value to it. JavaScript will not throw error on property creation.
var student = new Student();

//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property="set public content";

console.log(student.private_property);
Another point here to note is that you have created a public property of same name to the private property but class still maintain the private property with same value. So I was right in saying JavaScript is a race car you only need to know how to handle it.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };

    this.checkPrivatePropertyValue = function () {
        console.log(private_property);
    }
};

var student = new Student();
//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property = "set public content";

console.log(student.private_property);
student.checkPrivatePropertyValue();
Here is JsFiddle Demo

Static Functions


To create a Static method for the class, you can add it with the class name.
var Student = function () {
    this.first_name;
    this.last_name;
    this.courses = [];
};

Student.StaticMethod = function () {
    return "Here is static content";
};
Here is JsFiddle Demo

Now you can call it anywhere directly with the class name.

So in this article we explore to declare the different type of methods and properties. If you have any feedback please do write comments.

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