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 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.
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.
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.
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:
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;
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.
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
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
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
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);
};
// 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;
};
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
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
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.
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.
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());
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;
};
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());
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();
JavaScript is an excellent programming language. It is a race cars with so many gears, you just need to know how to handle it. JavaScript supports Object Oriented programming, it will not force it while compiling by throwing errors. But if you know how to write OOP code with JavaScript you can get all the aspects of OOP in JavaScript and believe me its amazing.
JavaScript supports object oriented programming because it supports properties, methods, inheritance through prototyping which are building blocks of OOP. Many developers avoid JavaScript because they are used to off writing OOP code with C#, Java or any other OOP programming languages and they don't know that JavaScript supports OOP and once you start writing code with JavaScript, It gives you encapsulated, re-usable and well managed object oriented code.
JavaScript Object Oriented Programming
Namespace
If you are C# or Java developer you must be familiar with Namespace. Namespace is a logical group of classes containing similar functionality under a unique name.In JavaScript Namespace is an object(namespace) which contains other objects, functions (classes). There is no difference in Namespace object and class object used in JavaScript unlike C# or other OOP languages.
Here is an example of namespace
// global namespace
var OOPJS = OOPJS || {};
Here in above code it is checking if namespace(object) of OOPJS is already existed within applications then use the same object but if it is not created then it create an empty object and initialize our object(namespace). Now this namespace is ready to contain the classes(function) and properties.
You can write your namespace helping function or common variables, functions across the namespace within this namespace.
// Create container called OOPJS.Helpers for common methods
var OOPJS = {};
OOPJS.Helpers = {
//common variables
global_variable: "Object Oriented Programming",
//common methods
myNamespace: function () {
return "OOPJS";
}
}
console.log(OOPJS.Helpers.global_variable);
console.log(OOPJS.Helpers.myNamespace());
JavaScript has many object (classes) available for use, like in C# there is Math object which contains static function abs(), round() etc, same concepts available in JavaScript. There are objects like Math, Object, Array, Number, Date, JSON, String and others.
See here a math object random() function which generate a random value.
console.log(Math.random());
Like Math there is object Object available which contains prototype, create() [ECMAScript 5 and above] and many others. Since specified built-in objects have the object referred to by Object.prototype in their prototype chain by default therefore all the properties and functions of Object is inherited to that object. Note all these methods and properties also inherited to namespace too since it is also an object.
So if you want to add a function to all the objects, you can add it to Object using prototype property.
Custom Classes/Objects
The Class
JavaScript contains no separate class declaration like C#, Java or other programming languages. In JavaScript class is a function which contains methods and properties.
Here is a class declaration:
function Person() { }
//or
var Student = function(){ }
Class Instance
To create an instance of class we use new keyword with the class name, which instantiate a new fresh instance of class.
Here we declare a class and then created two instance of the class.
function Student() { }
var student1 = new Student();
var student2 = new Student();
In next article we will see classes in details with different access modifiers and other aspects of Object Oriented Programming in JavaScript. Please comment your valuable feedback and suggestion for improvement of this post.
While working on a project, you do not want your uncompleted task code to cause a state where the project is not in the executable state. To overcome these situations you need project branches. Whenever you start a new task you create a new branch and write all your code to that branch and once you are done with task implementation and testing you merged that branch to the main branch and all developers now can access it.
To create branches and merging branches in Git lets see a workflow which we see while coding in our project. You’ll follow these steps:
You are working on a website.
Create a branch for a new issue/story.
Started implemented that issue fixes or story.
At this point, testing team found a critical issue on production and you must need to fix that issue at priority. Now you will:
Switch to Master/Production branch.
Create a branch to add the Patch.
After it’s tested, merge the Patch branch, and push to master branch.
Switch back to your original story and continue coding.
Git Branching
Initially, you are on the master branch where you already have some code commits.
You have started working on a new Story. You want to isolate your code from the master branch until the story is completely implemented and tested. So you will create a new branch for this story. To create a branch and switch to it at the same time, you can run the git checkout command with the -b switch:
$ git checkout -b story12
Switched to a new branch 'story12'
This is shorthand for:
$ git branch story12
$ git checkout story12
Now you work on the story and make changes to some files.
$ git add folder/file.html folder/file2.html
$ git commit -m 'added some new pages for story 12'
Now at this point testing team found a vulnerability in the website which needs to be fixed on urgent basis.You don't want to revert all your code you have written for Story 12 so now all you have to do is switch to master branch. But before switching to the master branch you need to commit or stash all your work otherwise, Git would not let you switch the branches until your current branch is not in a clean working state.
$ git checkout master
Switched to branch 'master'
Now you are at a point from where you started coding for story 12, so there is no extra code which is different from the code which is in production. So now you can create a new branch for Patch on which to code for the fix of vulnerability until it's completed and tested.
$ git checkout -b patch
Switched to a new branch 'patch'
$ vim design.html
$ git commit -a -m 'fixed the vulnerability'
Now when you are sure that fix has been completely implemented for the issues, you can merge your patch branch to master branch. You do this with the git merge command:
$ git checkout master
$ git merge patch
Now after complete testing you can deploy master branch to production.
Now when you are done with Patch fix and it's successfully deployed, you can switch back to your story which was incomplete. Here as you are done with Patch branch and you are sure that you won't need it now. You may delete it from Git. To delete it use the -d option to git branch:
$ git checkout Story12
Switched to branch 'Story12'
Here in Story12 branch, it has not the code you did for Patch branch. Now there are two options either you pull the master branch and merge master branch to your story12 branch immediately or you can wait until completion of Story12. It depends on the project requirement.
Basic Merging
When your story implementation is completed and tested and ready to be merged into the master branch. To merge the branch you have to check out the branch you wish to merge into and then run the git merge command:
$ git checkout master
$ git merge Story12
Auto-merging README
Merge made by the 'recursive' strategy.
README | 1 +
1 file changed, 1 insertion(+)
Now that your work is merged in, you have no further need for the Story12 branch. You can delete it:
$ git branch -d Story12
Merge Conflicts
Sometimes while merging there come a situation when two different branches have changed the same part of a file. In that case, Git shows the conflict in files where Git would not be able to merge them cleanly. If your Story12 branch and Patch branch have changed the same part of files then Git will prompt you a conflict:
$ git merge Story12
Auto-merging file.html
CONFLICT (content): Merge conflict in file.html
Automatic merge failed; fix conflicts and then commit the result.
Git won't automatically commit a new merge in conflict case. Here you need to resolve the conflicts of the files. If you want to see the files which are unmerged due to conflict, you can see it by:
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add ..." to mark resolution)
both modified: file.html
no changes added to commit (use "git add" and/or "git commit -a")
Git add the conflicts marker to files which has conflict like this:
<<<<<<< HEAD
Here is content
=======
Here is updated contact
>>>>>>> Story12
The code between <<<<<HEAD to ======= is the code which was in master branch while code from ======== to >>>>>Story12 is code from Story12 branch. Here you have to decide which code you want to keep safe and which to remove and once you completed resolving conflict.
You can run git status again to verify that all conflicts have been resolved:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD ..." to unstage)
modified: file.html
If you’re done with conflict resolution, you can add an commit the files:
$ git add file.html
$ git commit
Now merge the branch:
Merge branch 'Story12'
Conflicts:
file.html
#
# It looks like you may be committing a merge.
# If this is not correct, please remove the file
# .git/MERGE_HEAD
# and try again.
#
Git shows the default merge message you can edit and update with required details and information of merge.
Now you are done all of Story12 branch code, Patch branch and master branch is merged in the master branch.
Every software developer has to use the version control or revision control systems to better control of the project. Revision Control system maintains the history of changes to each document of a repository. When you start a project with a revision system it is at revision 1 and with each change revision increment. So at any time, you can go back to any revision.
There are many Version Control Systems (VCS) available to use which includes Git, SVN, CodeVille, Visual SorceSafe and much more. Here I am going to discuss the Git an open source version control system. Git is the distributed revision control system with an emphasis on performance. Git is most widely used revision control system.
What is GIT?
GIT is an efficient open-source Revision Control System. It tracks the changes history of the content such as files and directories. Git helps people to work together as a team, all using the same directories and files. It allows resolving the confusion that may occur when more than one person changing the same files by maintaining the history of each change from each user.
Git maintain the versions at local machine along with a remote machine, all changes firstly log at local machine of a user and when user push these changes it also gets logs on the remote machine.
How to Install Git?
If you are installing it on windows you can download it from GIT-SCM. It will download GUI software for Git a handy tool for the users who found command line difficult to use but also give you command line console.
For installation of Git via native packet manager for example, on Debian (or Ubuntu):
sudo apt-get install git-core
Or on installation on Mac OS X, using MacPorts:
sudo port install git-core+bash_completion+doc
or using fink (an effort to port and package open-source Unix programs to Mac OS X):
fink install git
or using Homebrew:
brew install git
On Fedora (Red Hat based distributions):
yum install git
Creating New Repository
Once you are done with installation of Git, you are ready to create a repository of your project. For creating a new repository\project, you need to setup a remote machine. To setup project remote server you need to run the following commands:
ssh your-remote-server@example.com #to connect with remote server
mkdir my_project_repository #create a directory for the project
cd my_project_repository #open new created directory
git init #create a git repository
exit
Now you are done with your server close your connection to the server and run the following commands on the local machine:
cd my_project_directory #open your project directory
git init #initialize git on the directory
git add * #add all files to the repository
git commit -m "My initial commit message" #commit with a message
git remote add origin your-remote-server@example.com:my_project_repository #set remote machine address to the local repository
git push -u origin master #push files to remote
Clone of Repository
Now your machine has configured, all of your team members can get the clone of the repository.
git clone your-remote-server@example.com:my_project_repository
cd my_project_repository
Now each team member can work on the same repository without worrying about changes being made to same files. Let the Git manage the history of each change to each file and anytime you can revert back to the revision.
Hope you found this article informative In next article we will see some more commands to handle repository like creating branches, adding new files, commit your changes and more. Please post your feedback in comments.
Every web developer needs to write CSS for making a site beautiful and attractive. CSS is easy but also tricky due to its different behavior on different browsers. The most annoying thing with CSS any developer face is the order of precedence in which CSS rule applied.
Let say there is a div with class and id, and there is css rule define for class, id and tag.
<div class="div-class" id="DivId">
Here is content div...</div>
<style>
d iv{
background-color:red;
width:100px;
height:100px;
}
#DivId{
background-color:green;
width:200px;
height:200px;
}
.div-class{
background-color:yellow;
width:300px;
height:300px;
}
</style>
So, which rule will be applied to div? Any guess! No Lets see demo.
Order of precedence of CSS rule
There is a specific order in which CSS applied to an element. This order can further be divided into two parts.
A. Placement Method of CSS
Style to any HTML element can be applied in three different legal ways.
As inline styles — css style directly applied to an element using style attribute.
CSS declaration overrides the other declaration in the order of precedence we listed above. Its means:
Inline styles have highest priority and it overrides all other rules if there is same property describe in other methods.
Embedded styles have less priority than inline style but it overrides the same propertied define in external stylesheets.
The External style sheet has lowest priority but it is the recommended way, as it separates the CSS from HTML and make it easy to manage CSS in one place. If there is more than one external style sheet than priority decided in the way files included in HTML, first file (top) has lowest priority while the last file included (at bottom) has greater priority.
B. CSS Selector Precedence
Within any of above method precedence is different for the CSS selector used. As we see in the first example in this post. A div having three different rules for different selector will result in only one of three CSS selector. The order of precedence of the various CSS selectors are:
ID Selector
ID is restrictive attribute, valid HTML page contains only one element with a specific ID. That is the reason ID selector has the highest priority. Which means a CSS rule in external CSS file will override all other CSS rules with the same properties for any element. Similarly the CSS rule define for ID in embedded style will override other rules in embedded style.
#DivId
{
background-color:red;
}
Attribute Selector
In priority order second selector is attribute selector, in which we define CSS for the element which has a specific attribute value. It also has the same scope for external and embedded styles as for ID.
Adjacent Sibling Selector two elements sibling to each other
#DivId + ul { }
Descendant Selector child at any level under parent tag
ul li { }
Type Selector tag name
li{ }
Order of declaration
Beside above given rules of precedence, CSS follows the descending fashion to apply CSS rule means if there are two different rules for the same class, will result the last rule to be applied
.aClass{
background-color : yellow;
}
.aClass{
background-color : red;
}
//this last one will override above ones
.aClass{
background-color : green;
}
<a class="aClass" href="http://goo.gl/DnIh3A">Angular JS
The !important Rule
There can be a situation when we need to override the CSS in less priority place. Like if there is a width property assigned in inline CSS and we need to override in External Style Sheet or width property set in ID selector and we want to override it in class selector then we use !important with the rule we want to have higher priority.
So here we are with fifth part of the series, In previous article we see modularity and controller, config, factory of an AngularJS application. In this post we going to see routing or views switching in more details.
Why we need Routing?
First question here is why we need routing as we are working on Single Page Application (SPA). Answer is simple! yes we are working on SPA but user friendly URLs really help in reaching correct page instantly, it also help when your user bookmarks a particular view.
If we have our site http://www.example.com and we are showing the same URLs for all of our page then if user bookmark this URL, on next visit he will again the same URL now your application really not know what user is expected view so application will show home page which is not user friendly way.
Instead this if we show http://www.example.com/aboutus or http://www.example.com/order etc and attach these URL in your application to a particular view templates than it is really helpful and user-friendly.
So routing actually give a logical name to your application's views and bind them to a particular controller.
Routing -Views
How to route in AngularJS?
In previous post we have seen a bit of routing using ngRoute, but in this post we will see routing with UiRouter because UI Router is more powerful and is updated with more advanced feature along with basic functionality ngRoute provide, like Nested Views, multiple named view etc.
For setting routing, Firstly we nee uiRouter library you can download it from here or can use CDN hosted library then we need to add directive ng-view to the main (index.html) view.
It work as a placeholder where all the html will be injected on a fly when particular url will be hit. For instance when user navigate to /#AboutUs , the view linked with AboutUs route will be injected to this placeholder, similarly other route will works.
Now we need add routes to config so we can associate views to urls and also while routing to views we pass the controller to the views.
//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'
},
aboutUs= {
url: '/aboutus',
templateUrl: 'views/AboutUs.html',
controller: 'AboutUsCtrl'
},
contactUs= {
url: '/contactus',
templateUrl: 'views/ContactUs.html',
controller: 'ContactUsCtrl'
};
//Now add these route state privider
$stateProvider
.state('home', home)
.state('aboutus', aboutUs)
.state('contactUs', contactUs);
}]);
Now we add our views and place them in app/views/ folder also we need to add controllers to application module, if we do not need any controller like we just need to show some view which has nothing to show from controller then we can remove controller from above given object but usually each view has some controller to communicate. we can add controller like we have seen in previous post.
myDemoApp.controller('HomeCtrl', function ($scope) {
$scope.message = 'Hello! we are on Home Page';
})
.controller('AboutUsCtrl', function ($scope) {
$scope.message = 'Hello! we are on About Us Page';
})
.controller('ContactUsCtrl', function ($scope) {
$scope.message = 'Hello! we are on Contact Us Page';
});
Now add three html files in views folder in app directory for each route and add html required in each view.
{{message}}
Now we have added everything we needed, save all files and try accessing url application with above configured urls. It must render particular views on different routes.
Master Pages in AngularJS
Master Page is the concept used in ASP.NET, It is the base templates where we put all the common functionality which we need to show on all the pages, so instead repeating same code on all page we create a base page where we code required html, and inherit all pages from this base. Now all pages start showing within this template. These common views can be site log, top navigation, sidebar, logged in user information, footer etc.
We can also achieve this Master Page concept in AngularJS. Lets see it with an example:
Here in above example there are four different layers of views:
Main View with Primar Navigation (Nav Link 1, Nav Link 2 ....)
Second Level View with Sub-Navigation (One, Two, Three ...)
Third Level View with Side Navigation (link1, link2, link3)
Most inner View with content
To achieve this we define a hierarchy of routes.
For example:
/#NavLink1/One/Link1
/#NavLink2/One/Link1
/#NavLink1/Two/Link1
/#NavLink1/Two/Link2
and similarly for all other pages.
angular.module('demoMasterPage', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {
var NavLink1 = {
//Name must be in format Parent.Child
name: 'NavLink1',
url: '/Navlink1',
templateUrl: 'views/Navlink1.html',
controller: 'homeCtrl'
},
NavLink2 = {
name: 'NavLink2',
url: '/Navlink2',
templateUrl: 'views/Navlink2.html',
controller: 'homeCtrl'
},
NavLink3 = {
name: 'NavLink3',
url: '/Navlink3',
templateUrl: 'views/Navlink3.html',
controller: 'homeCtrl'
},
NavLink1One = {
name: 'NavLink1.One',
url: '/Navlink1/One',
templateUrl: 'views/Navlink1/One.html',
controller: 'homeCtrl'
},
NavLink1Two = {
name: 'NavLink1.Two',
url: '/Navlink1/Two',
templateUrl: 'views/Navlink1/Two.html',
controller: 'homeCtrl'
},
// similarly for NavLink1Three,NavLink1Four, NavLink2One, NavLink2Two and so on.
NavLink1OneLink1 = {
name: 'NavLink1.One.Link1',
url: '/Navlink1/One/Link1',
templateUrl: 'views/Navlink1/One/Link1.html',
controller: 'homeCtrl'
},
NavLink1OneLink2 = {
name: 'NavLink1.One.Link2',
url: '/Navlink1/One/Link2',
templateUrl: 'views/Navlink1/One/Link2.html',
controller: 'homeCtrl'
};
//Similarly define all the combination you want to separate
//add routes to stateProvider
$stateProvider.state('NavLink1', NavLink1)
.state('NavLink2', NavLink2)
.state('NavLink3', NavLink3)
.state('NavLink1.One', NavLink1One)
.state('NavLink1.Two', NavLink1Two)
.state('NavLink1.One.Link1', NavLink1OneLink1)
.state('NavLink1.One.Link2', NavLink1OneLink2);
}])
.config(function ($urlRouterProvider) {
//set default page to redirect; if wrong route is given redirect here
$urlRouterProvider.otherwise('/NavLink1/One/Link1');
});
Add different html pages for each views, If view contains a child view so we need to ng-view to that view, except level4 which has no further child views. Here is index.html:
Similarly One will contain navigation and ng-view so it can redirect to child views. Create all the pages and save them in right places and then try your application in browser and see the impact of different routes.
This above example can be optimized in many ways which you will learn as you have more experience in working with AngularJS
So hope now you have clear picture of routing in AngularJS if you have any confusion, question, suggestion or feedback please comment.
So here I am with the fourth article in the series of Learning AngularJS a guide for beginners. If you have not read the previous articles I recommend you to read in sequence, it will help you in understanding more quickly. In this post we will see the modularity of AngularJS Application.
Before starting the real topic we need to see SPA (Single Page Application).
So what is SPA?
Single Page Application(SPA) or also called Single Page Interface (SPI) is a web application in which we have only one main view which is able to load many small pages on a fly, providing enhanced desktop application like fluid user experience.
Traditional web application gives a blink and load impact when we route from one page to another while in SPA we load a main page on first time then we never post back completely instead we load partial or small HTML pages which make it faster and give it a better user experience.
AngularJS application are Single Page Application, we have a main container page index.html load on first go then we only load the views which we required. To load the view at run-time we need to handle routing which is one of the main SPA concepts.
In the previous post we see the directives, filters and data bindings, so now we will see AngularJS as a complete module and how controller, model views, directives, routes actually fit into this module.
we define module for our application as:
<html ng-app="moduleName" >
and in JavaScript we create an object for our module as:
var moduleName = angular.module('moduleName', [ ] );
Defining ng-app on html tag will create a scope for angular application to the HTML and within this HTML scope angular directives , filters and data bindings will work. Since we are working on SPA application so having ng-app on html tag will scope whole application because when this page gets loaded then we not actually loading another page instead we loading partial views which get renders within this main page.
Now we have define the module for our application now we need to add config, controllers, directive, services to our module. Module in actually a container in which we bundle all of our same functionality.
Different module can also interact with each other. If you noticed the empty array passed to the module function with module name is the dependency injection we discussed in our first post. Here we can inject helping module or the module our application depends on. Like for route management we have many already written module available, we just need to pass the module object to our module and then we can use it within our application. We can define multiple modules:
// Define sub modules with no dependencies
angular.module('AccountApp', []);
angular.module('LoginApp', []);
// define main module and inject all other modules as dependencies
angular.module('MainApp', [
'AccountApp',
'LoginApp']);
Firstly we set config to our application module in which we can configure routing (we will see in details later). For this we just need to set config in module object.
//we passed ngRoute is an external module for handling routing
var moduleName = angular.module('moduleName', ['ngRoute']);
moduleName.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
});
});
If you noticed here we also passed the controller to the view previously we declare the controller for a view within the view but that is not a recommended way as we said in Model View Controller view should be independent of controller so it must not be dependent on controller, so better way is to pass controller to view on the fly when we routing to view.
Now View has the controller scope so it can access the scope variables of controller. We also need to add controller to our application module, for this we simple need to add controller to main module object.
// create the controller and inject Angular's $scope
moduleName.controller('mainController', function ($scope) {
// create a message to display in our view
$scope.message = 'Hello friend I am Main Controller';
});
Here in this simple application we do not required a service or factory but in application when we interacting with APIs then we need to create factory [or services, provider, value]. These four are for same things with some different features. As we might need to get User data from server using AJAX calls and we may need it in five different controllers so instead of repeating the same code for fetching user's data in controllers we move this to User Service and then call this service from different controllers.
We can define factory to our application using:
moduleName.factory('MyService', function () {
var factory = {};
factory.getUser = function () {
//..
}
return factory;
});
So lets review a complete cycle of angular application. Our application is a single module. It has configured routes when a particular URL get hit, it will be routed to specific View and Controller is also passed to the view at routing. Now View has the scope access of particular controller. It will call the controller for data. Controller will hit the service for data and service will send back data to controller fetching it from server. Controller pass that data to View and View render it accordingly.
So It was concept of modularity in AngularJS application. If you have any confusions or feedback or If you want to see any particular topic regarding AngularJS in this series please comment below.
Continuing the series of Learning AngularJS a guide for beginners, in this post we will see the Directives Filters and Data Bindings. If you are new to AngularJS I would recommend you to read the series of article from start.
To start developing an application you need to download AngularJS Library or you can use CDN for the benefits of caching. include the downloaded AngularJS to your HTML just before the closing body tag this will make sure that your document is loaded when your AngularJS start running.
That is it! you have everything you need to code for AngularJS application. You can use any IDE for coding I would recommend Visual Studio 2013 because of some better JavaScript intellisense.
Now you have included library for AngularJS you are ready to code, to code with AngularJS you need to use Directives.
What are Directives?
Directives are most important or I would say core components of AngularJS. Directives are nothing but HTML tags and attributes. These are the way to use AngularJS extended HTML functionality. Using directives you can teach HTML new features by writing your own custom directives. AngularJS comes with a bunch of built-in directives like ng-app, ng-hide,ng-show, ng-repeat, ng-class and many others.
Directives are markers on the HTML page that tells AngularJS to bind that particular directive functionality(behavior) on a specified element.
Lets see a simple Hello World application:
<html ng-app="">
<head>
<title>Anular JS</title>
</head>
<body>
<div id="container" ng-init="name='Zaheer Ahmed'">
Your Name: <input ng-model="name" type="text" />
Hello AngularJS world!!!!
My Name is {{name}}.</div>
</body>
</html>
So Here we have designed a simple application and we use some AngularJS directives, attributes starting with ng are angular directives.
We started with ng-app the most important directive of AngularJS.
It declares the scope of your application that is the reason it is mostly put at the html tag itself, but it can be use inside html the only thing need to be considered is that AngularJS directive only works within the scope of ng-app directives.
Here we use ng-app attribute without value because for this simple application we do not have any controller or scope (view model). So it works withing this scope. But if we want to use data from this view in our controller then we need to initialize value for this attribute i.e, ng-app='myApp'.
Then we used the ng-init let see it after ng-model, ng-model directive initialized a property in memory with the name given as value, ng-model is one of the ways to bind the $scope(View-Model) properties to the element, since in this example we do not have any controller so the scope of this variable will only be limited for this View.
Since we have pre-initialize the variable name using ng-init so it is already available in the memory so it will use this value and bind it to input input field. So when you run this application you will see input has value 'Zaheer Ahmed' because name was initialize by it.
So these are some basic directive you mostly need to use, as you start practicing you will get familiar to many built-in directives. Here is complete API reference available, you can search and get information about all directives or you can download Angular Cheat Sheet.
Data Binding
Data binding in AngularJS is really simple, as we did in above code simply wrap the variable as {{variable}} on any element, that element is now bounder to the data. ng-model is also a way to bind using attribute as we did in above code example.
Binding in AngularJS is two ways which means if you bounded an element to a data now if that element lets say input change that property the original data in your controller will also be updated or if you update the value of data from controller element will also show changes.
So AngularJS made this so simple using one attribute otherwise developer need to write the code to detect onchange event for getting change from element and also need to update element to update element value.
How Filters work?
Filters are the way to pass all of your data collection to a particular condition. like searching, sorting etc. For example in above code we printed the name enter by user in input field we want to make it upper-case or there is an array we want to upper-case all string there we need to use filters. Filters are applied on a data using bar separator.
So changing above code to :
<html ng-app="">
<head>
<title>Anular JS</title>
</head>
<body>
<div id="container" ng-init="name='Zaheer Ahmed'">
Your Name: <input ng-model="name" type="text" />
Hello AngularJS world!!!!
My Name is {{name | uppercase}}.
</div>
</body>
</html>
above code will automatically convert input value to upper-case. Here is demo.
Let see another example where we filter data using user input:
<html ng-app>
<head>
<title>Anular JS</title>
</head>
<body>
<div id='container' ng-init="names=['Ahmed','John','Jeff',Zaheer']">
search : <input type="text" ng-model="searchKeyword" />
<div style='background:#E4E8EA;padding:10px;'>
Here is list of user name:
<ul ng-repeat="name in names | filter:searchKeyword">
<li>{{name | uppercase}}</li>
</ul>
</div>
</div>
</body>
</html>
Here we initialize an array using ng-init directive and bind input field with another variable searchKeyword like we did in our previous example.
Here we used another directive ng-repeat, this directive keeps repeating element to the number of times data present in given collection. This is really helpful for-example you have 50 users data and you want to show in a particular format. You need to write 50 times the same HTML but with ng-repeat you just need to create a template and using this directive repeat it number of times you want.
Now here we use the filter after bar separator name in names | filter:searchKeyword here we are telling it to filter the collection for searchKeyword, so it will give us only the list containing the keyword input by user.
As you see how simple it was to filter a collection. There are many built-in filters available which include currency[:symbol], filter:expression, json, lowecase, uppercase, orderby etc.
So it was Directives filters and data binding in AngularJs. Hope now you have some base knowledge and with time and practice you will be familiar with more of these.
Hope you find this helpful. Please do comment if you want to see any particular topic of AngularJS in this series and also give your valuable feedback and don't forget to share with friends.
So here we are with the second part of the series learning AngularJs guide for beginners. If you have not read the first Article I strongly recommend you to see the first article of the series Introduction to AngularJS
In this article we are going to see Models Views and Controllers and will see model part of the application also called View Model or $scope in details. It is a really important part of AngularJs.
View Controller and Scope
Views
The AngularJS application has a View which is the part rendered in a browser, it is the way to show the data to users. View uses the directives, filters and data-bindings. But to make view simple and easy to maintainable we do not put all of our code into these View. Separating code from views also make it easy to write tests for the business logic.
Controller
We put all of our logic to container called controller in Angular. The Controller controls and prepare the data into the form so it can be rendered at the View. So Controller actually transforms the bunch of data into the representational form and also take from view and set into the Model after validating it. The controller is responsible for communicating the server code to fetches the data from a server using Ajax calls and send the data to back-end server from Views.
Scope / View Model
The most important part of the architecture is $scope or Model or View Model. It is the actual link between Controllers and Views. There can be a controller which we can bind to two or more views. Like controller for a registration form can have a different view for desktop and another view for mobile. In real Controller has no information about the Views and similarly View is independent of logic implemented or data present in the Controller. $scope acts as the communication tunnel between the Views and Controller.
First Code Example
We will try to implement a simple demo, so it becomes more easier to understand the concept of View Controller and scope. In this simple example we list down the Users. You will definitely find very easy to implement it.
Here is the code of View:
<div ng-controller="MyFirstController">
<h2>List of User</h2>
<ul>
<li ng-repeat="user in Users">
{{user.firstName}} {{user.lastName}} live in {{user.city}}
</li>
</ul>
</div>
Here we are using some AngularJS directives we will see these directives in later articles. Just to make it understand we are telling view that you expect data from this controller using ng-controller directive. It is not necessary to declare a controller here we can set it at run-time with routing.
Here we initialize an angular module application myApp and then added a controller to it. This controller contains a list of users. Then we access the controller and show the list of user in HTML View.
So this was the architecture use in Angular, It is really easy to maintain and much cleaner than ordinary dynamic application code. In next article I will try to cover directives filters and data bindings. Please provide your valuable feedback by comments and let me know if any particular topic you want to see in this series. Don't forget to share it with your friends.
Recently I started learning AngularJs, It was very difficult for me to find some good detailed articles or beginner tutorials on AngularJS. I have to read from many different articles, books and tutorials. So I decided to put step by step help for beginners like me. So they get complete required help from one single channel. Since AngularJS is a very rich framework so I decided to write in a series of post. So beginners easily follow and track their performance.
Lets start with Introduction to AngularJs. There is no coding in this article we will only see what AngularJs is.
What Is AngularJS?
AngularJS is JavaScript MVC structured framework for dynamic web applications. It is created by Google to allow you to develop well architectures and easily maintainable web-applications. AngularJS allows you to extend HTML by adding your own custom tags and attributes. With angularJS you need to write lesser code as It allows you to reuse components. With very easy way of two-way bindings and dependency injection (we will see these in details coming articles) , you need to code less than you have to write before AngularJS. As AngularJs is client-sided so all these things happening in browsers.
HTML is designed for static sites, it is beautiful declarative language. But developing a dynamic site with HTML you need to do many tricks to achieve you want. With AngularJS extending the HTML it is really simple to make a dynamic site in a proper MVC structure. The directive is the terminology use for extending HTML, with these directives one can achieve:
You can create a template and reuse it in application multiple times.
Can bind data to any element in two ways, means changing data will automatically change element and changing element will change the data.
You can directly call the code-behind code in your html.
Easily validate forms and input fields before submitting it.
You can control complete dom structure show/hide, changing everything with AngularJS properties.
AngularJS a complete Solution
AngularJS not only allow you to write your custom HTML. It allows you to completely control your DOM and easily managed your Ajax code which previously you need to manage your own. It has included many other features including:
All the features you need to build a CRUD application like data-binding, data validation, url routing, reusable HTML components and most importantly dependency injection.
JavaScript Testing: AngularJS allows you to write basic flow end-to-end testing, unit-testing, ui mocks.
Proper directory architectures of HTML code in MVC structure.
Until now we use term dependency-injection many times, some of you might not be aware of it. Dependency Injection is a software design pattern, allows you to inject any dependent module at run time means you can anytime change some feature or complete module of any dependent module with this pattern. AngularJs also follow the dependency-injection for example you can change the routing module with your custom written library or may switch many available pre-written libraries for routing.
If you were previously coding with jQuery you might use it for many features which AngularJS already included in it, so instead of depending on two different libraries which is possible to achieve with only having AngularJS, It is better to not include the jQuery file in your page (until it is really necessary) because with AngularJS $http service and rich directive it makes jQuery useless. With AngularJS one thing is sure you have not much cleaner and structured code than jQuery.
This was a short AngularJS introduction in the next article we will see the MVC in AngularJS. So keep commenting the topics you want to see in this series of article so I include articles accordingly.
Currying is technique mostly mentioned in functional programming as function currying.
What is Functional Programming?
Functional programming is a programming paradigm which primarily uses functions as means for building abstractions and expressing computations that comprise a computer program.
Confused! ok you do not need to understand what functional programming is for understanding currying. so ignore it.
What is currying?
Currying is to transform a function with many parameters to a function with less parameters or in other words, process of transforming a function with N parameters to a function that takes less than N parameters.
For example, a function takes A, B, C arguments and returns R as result i.e { A , B , C => R } currying allow you to change it to a function which takes only A as argument and returns you a function which take B as argument and this second function takes B as argument and returns a function which takes C as arguments and this last method takes the argument C and returns you the Result R.
{A => { B => { C => R } } }
The curried effect is achieved by providing some of the arguments of the main function at first invocation, so that those values are fixed for the next invocation.
var teacher = function(teacherName){
return function(subject){
console.log(teacherName+' teaches '+subject);
}
}
var aliceTeach= teacher('Alice');
aliceTeach('JavaScript');
aliceTeach('Data Structures');
Here we used the concept of JavaScript Closure (Closure allows you to use Parent scope variable in inner functions. ), first function takes the parameter teacherName and use this as closure in inner-function and return the function which has fixed value for teacher name but expecting subjects name. Since teacherName is prefilled, now calling function with subject has fixed teacher name with it.
Currying is helpful where your some arguments are fixed for certain module or series of function. For example you write a function that add two numbers (see demo):
function add(x,y){
console.log('Sum is : '+(x+y));
}
add(4,2);
but what if there is situation you need to add 4 to different numbers, means your first argument is fixed. If you implemented without currying like above you need to write:
add(4,10);
add(4,21);
add(4,83);
...
There is a chance of mistake in passing some other argument instead of 4 if not still it is redundant to pass same argument many times.