Tuesday 24 May 2016

the calling order in angular js

Here's the calling order:
  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
Example:
index.html
<div ng-app="myApp" ng-controller="myCtrl">
    <div test1 test2> </div>
</div>
index.js
var myApp = angular.module('myApp', []);
myApp.factory('aProvider', function() {
   console.log("factory");
});
myApp.directive("test1", function() {
    console.log("directive setup");
    return {
        compile: function() {console.log("directive compile");}
    }
});
myApp.directive("test2", function() {
    return {
        link: function() {console.log("directive link");}
    }
});
myApp.run(function() {
    console.log("app run");
});
myApp.config( function() {
    console.log("app config");
});
myApp.controller('myCtrl', function($scope) {
    console.log("app controller");
});

Order Of execution:
app config
VM61:64 app run
VM61:51 directive setup
VM61:53 directive compile
VM61:72 app controller
VM61:59 directive link

Difference between constant and value

A constant can be injected anywhere.
A constant can not be intercepted by a decorator, that means that the value of a constant should never be changed.
var app = angular.module('app', []);

app.constant('PI'3.14159265359);

app.controller('appCtrl'function(PI) {
    var radius = 4;
    // calculate area of the circle
    var area = PI * radius * radius;
});
Value differs from constant in that value can not be injected into configurationsbut it can be intercepted by decorators.
var app = angular.module('app', []);

app.value('greeting''Hello');

app.config(function ($provide) {
    $provide.decorator('greeting'function ($delegate) {
        return $delegate + ' World!';
    });
});

Wednesday 18 May 2016

Template rendering by using ng-include directive

Ng-include:
Fetches, compiles and includes an external HTML fragment.

template1.html
<h1> Hello !! I am from template1 </h1>

Index.html
<div ng-controller="ExampleController">
  <h1>Hello From index</h1>
  <div>
    <div ng-include="template1.html "></div>
  </div>
</div>

Output:

Hello From index
Hello!! I am from template1


Monday 16 May 2016

How to efficiently check if variable is Array or Object


How to efficiently check if variable is Array or Object

a = [1,2,3]
[1, 2, 3]
a.constructor === Object
false
a.constructor === Array
true
a = [1,2,3]
[1, 2, 3]
a = {'name' : 'ggg', 'age': '52'}
Object {name: "ggg", age: "52"}
a.constructor === Array
false
a.constructor === Object
true

Wednesday 4 May 2016

Reuse html code snippet in angular

<script type='text/ng-template' id="mySnippet"> 
   <h1> Reuse this template </h1>
</script> 
<ng-include src="'mySnippet'"></ng-include>
<ng-include src="'mySnippet'"></ng-include>

script

Load the content of a <script> element into $templateCache, so that the template can be used byngIncludengView, or directives. The type of the <script> element must be specified astext/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.

Friday 22 April 2016

factories in angular

Factory is used for large code but to expose some of the variables and functions that are useful. factory return an object.

Syntax:

myModule.factory("factoryName", function(){
//code goes here
return {
// functions/varibles to expose
}
});


Example:
angular.module('myApp.factory',[]).factory('myfactory', function(){
function calculteArea(s) {
var area = s * s;
alert(area);
}
return {
areaOfScure: calculteArea;
}
});

Inject factorynamr in controller to use it's methods.

angular.module('myApp.controller',[]).controller('demoController1',['$scope','myfactory',function($scope, helloService){
myfactory.areaOfScure(10);
}]);

output:

return an alert with 100 as area.



services in angular

Service:

Services is a singleton object. It will create instance only for the first time, after that it will reuse that object.

syntax:
angular.module("module_name").service("service_name", function(){
//constroctor function
})

Example:
angular.module('myApp.service',[]).service("helloService", function(){
this.name = "saritha",
this.company = "cts"
this.display = function(){
alert(this.name);
}
});

Inject this service module into another module to reuse.

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


In controller we can use it as:

angular.module('myApp.controller',[]).controller('demoController1',['$scope', 'helloService',function($scope, helloService){
helloService.display();
}]);

output: output the alert

advantages:
Easy to create object,
Less time to execute,
Reusabuluity

drawbacks:
It is very difficult to execute for larger code.

Thursday 21 April 2016

Constant in angular:


A constant can be injected everywhere. A constant can not be intercepted by a decorator, that means that the value of a constant should never be changed (though it is still possible to change it programmatically in Angular 1.x).

Syntax:
.constant(name, value);

name --> name of constant
value --> value of constant

Example:

var myAppangular.module('myApp', []);

myApp.constant("clientId", "123456");

myApp.config(['clientId', function(clientId){
console.log(clientId);
}])

myApp.controller('myController',['clientId', function(clientId){
console.log(clientId);
}])

so, the difference between constant and value is constant inject in  config block but value can't

Value in angular:

A value is nothing more than a simple injectable value. The value can be a string, number but also a function. Value differs from constant in that value can not be injected into configurations, but it can be intercepted by decorators.

Syntax:
module_name.value('name', 'value')

name --> instance name
value --> the value of instance

Example:

1, Create a module
var myApp = angular.module('app', []);

2. Add value to module

myApp.value("clientId", "123456");

3, Inject value to your controller function to use it

myApp.controller('MyController', function (clientId) {
  console.log(clientId);
});

Routing in angular js

1, download angular-route.min.js from https://code.angularjs.org/1.5.5/
2, include angular-route.min.js file to your application using script tag
   <script src="angular-route.js">

3, Then load the module in your application by adding it as a dependent module:
   angular.module('myApp', ['ngRoute']);

With that you can use all the methods, providers, services in ng-route module

ngRoute:
The ngRoute module provides routing and deeplinking services and directives for angular apps.

ngView:
ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

Example:

1, Create 2 html files named as route1.html and route2.html respectively in views folder.
2, inject ngRoute module to myApp module.
   angular.module('myApp', ['ngRoute']);

3, In config use $routeProvider to configure routes
   angular.module('myApp', ['ngRoute']).config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/route1', {
templateUrl: 'views/route1.html',
}).when('/route2', {
templateUrl: 'views/route2.html',
});
   }])
4, In index.html create two links use anchor tag.
<a href="#/route1">route1</a> |
  <a href="#/route2">route2</a>
5, Add ng-view in index.html
<div ng-view></div>

that's it...now refresh your index.html and then check it.. :-)

custom filters in angular:


syntax:
angular.module("module_name").filter('filter_name'), function( dependencie_if_any){

});

Example:
//uppercase is a predefined filter we are passing as a dependency injection, so that we can use it in controller.

angular.module('myApp').filter('capitalize',function(uppercaseFilter){
return function(input,a){
console.log(a);
var result = null;
if(typeof(a) == 'undefined'){

result = uppercaseFilter(input[0])+input.substring(1,input.length);
} else{
result = input.substring(0,a-1) +uppercaseFilter(input[a-1])+input.substring(a,input.length);

}
return result;
}
});


in index.html we can use it as:

{{"saritha chakilala" | capitalize}}
output: Saritha chakilala

[["saritha chakilala" | capitalize : 2]]
sAritha chakilala

Tuesday 19 April 2016

number filter in angular:

If the input is null or undefined, it will just be returned. If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively. If the input is not a number an empty string is returned.

syntax: {{ number_expression | number : fractionSize}}

Ex:

Task1 : 

{{ 12345.625252 | number }}

output: 12345.625

Task2 :

{{ 12345.625252 | number:2 }}

output: 12345.62

Task3:
{{ 12345.625252 | number:0 }}
output: 12346

lowercase and uppercase filter in angular

lowercase filter in angular:
To convert string to lowercase

syntax: {{ string_expression | lowercase}}
Ex: $scope.message = "hello from angular."
{{message | lowercase}}


uppercase filter in angular:

syntax: {{ string_expression | uppercase}}
To convert string to uppercase
Ex: $scope.message = "hello from angular."
{{message | lowercase}}

currency filtr in angular:

This filter is used to format the number to currency ( i.e, to display $/Rs symbol infront of number and specify number of decimals after floating point )

Ex:

$scope.amount = 1234.56

syntax:
{{ currency_expression | currency : symbol : fractionSize}}

Note: default symbol for currency is $, and default fractionSize is 2

Task1:
<h1> {{ amount | currency}} </h1>
o/p: $1234.56

Task2
<h1> {{ amount | currency:"USD$"}} </h1>

o/p: USD$1234.56

Task3: 

<h1> {{ amount | currency:"USD$":3}} </h1>

o/p: USD$1234.560

oredr by filter in angular:

This filter used to order elements in ascending / descending.

$scope.lists = [{name:'sai',company: 'CTS'},{name:'kiran',company: 'cognizant'},{name:'sai kiran',company: 'cognizant'},{name:'sai krishna',company: 'we'}]

Task1: ascending order

<ul>
<li ng-repeat="a in lists | filter:search:strict | orderBy : 'name'">[[a.name]]</li>
</ul>

Task2: descending order

by default order by ascending, to order  in descending use '-' symbol before attribute

<ul>
<li ng-repeat="a in lielementssts | filter:search:strict | orderBy : '-name'">[[a.name]]</li>
</ul>

Monday 18 April 2016

filter in angular

filter:

Select a subset of items from an array.

ex:
$scope.lists = [{name:'sai',company: 'CTS'},{name:'kiran',company: 'cognizant'},{name:'sai kiran',company: 'cognizant'},{name:'sai krishna',company: 'we'}]

task 1:

<label>Search: <input ng-model="searchText"></label> (searches any field)
<ul>
<li ng-repeat="a in lists | filter:searchText"> {{a.name}}</li>
</ul>

task2:

<label>Search By Name: <input ng-model="name"></label>
<ul>
<li ng-repeat="a in lists | filter: {name: name}">{{a.name}}</li>
</ul>

task3:
<input ng-model="search.$"> (searches with any field(i.e, name/ company))
<input ng-model="search.name"> (searches with name field)
<input ng-model="search.company"> (searches with company field)

<ul>
<li ng-repeat="a in lists | filter: search ">{{a.name}}</li>
</ul>

task4: (case scensitive filtering)

<ul>
<li ng-repeat="a in lists | filter: search : true">{{a.name}}</li>
</ul>

Friday 15 April 2016

Get Started with angularJS:


1, go to https://angularjs.org/
2, download angular.js file from above site and place it in our application lib folder
<script src="lib/angular.min.js"></script>
{or}
  directly copy CDN and use it with script tag
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
3, sample application to test
<html>
<head><title></title></head>
<body>
{{10+5}} //angular expression
</body>
</html>

when we open application in browser it wont interpret angular expression.

To make our webpage angularize we need to include ng-app directive

<html>
<head><title></title></head>
<body ng-app>
{{10+5}} //angular expression
</body>
</html>

Sunday 10 January 2016

Ruby Variable Scope

What is Variable Scope?

Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, localglobalinstance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table.

Name Begins WithVariable Scope
$A global variable
@An instance variable
[a-z] or _A local variable
[A-Z]A constant
@@A class variable
In addition, Ruby has two pseudo-variables which cannot be assigned values. These are nil which is assigned to uninitialized variables and self which refers to the currently executing object. In the remainder of this chapter we will look at each of these variable scopes in turn.

Detecting the Scope of a Ruby Variable

Obviously, you can tell the scope of a variable by looking at the name. Sometimes, however, you need to find out the scope programmatically. A useful technique to find out the scope of a variable is to use the defined? method. defined? will return the scope of the variable referenced, or nil if the variable is not defined in the current context:
x = 10
=> 10
defined? x
=> "local-variable"

$x = 10
=> 10
defined? $x
=> "global-variable"

Ruby Local Variables

Local variables are local to the code construct in which they are declared. For example, a local variable declared in a method or within a loop cannot be accessed outside of that loop or method. Local variable names must begin with either an underscore or a lower case letter. For example:
loopcounter = 10
_LoopCounter = 20

Ruby Global Variables

Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared. Global variable names are prefixed with a dollar sign ($). For example:
$welcome = "Welcome to Ruby Essentials"
Use of global variables is strongly discouraged. The problem with global variables is that, not only are they visible anywhere in the code for a program, they can also be changed from anywhere in the application. This can make tracking bugs difficult.
It is useful to know, however, that a number of pre-defined global variables are available to you as a Ruby developer to obtain information about the Ruby environment. A brief summary of each of these variables is contained in the following table.

Variable NameVariable Value
$@The location of latest error
$_The string last read by gets
$.The line number last read by interpreter
$&The string last matched by regexp
$~The last regexp match, as an array of subexpressions
$nThe nth subexpression in the last match (same as $~[n])
$=The case-insensitivity flag
$/The input record separator
$\The output record separator
$0The name of the ruby script file currently executing
$*The command line arguments used to invoke the script
$$The Ruby interpreter's process ID
$?The exit status of last executed child process

For example we can execute the gets method to take input from the keyboard, and then reference the $_ variable to retrieve the value entered:
irb(main):005:0> gets
hello
=> "hello\n"
irb(main):006:0> $_
=> "hello\n"
Alternatively we could find the process ID of the Ruby interpreter:
irb(main):007:0> $$
=> 17403

Ruby Class Variables

A class variable is a variable that is shared among-st all instances of a class. This means that only one variable value exists for all objects instantiated from this class. This means that if one object instance changes the value of the variable, that new value will essentially change for all other object instances.
Another way of thinking of thinking of class variables is as global variables within the context of a single class.
Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time. For example:
@@total = 0

Ruby Instance Variables

Instance variables are similar to Class variables except that their values are local to specific instances of an object. For example if a class contains an instance variable called @total, if one instance of the object changes the current value of @total the change is local to only the object that made the change. Other objects of the same class have their own local copies of the variable which are independent of changes made in any other objects.
Instance variables are declared in Ruby by prefixing the variable name with a single @ sign:
@total = 10

Ruby Constant Scope

Ruby constants are values which, once assigned a value, should not be changed. I say should because Ruby differs from most programming languages in that it allows a constant value to be changed after it has been declared, although the interpreter will protest slightly with a warning message.

Constants declared within a class or module are available anywhere within the context of that class or module. Constants declared outside of a class or module are assigned global scope.