Share the data between Parent Directive to Child Directive.!

<!–  HTML –>

<html ng-app=”understandMe”>
      <body>
            <country></country>
      http://js/angular.js
      http://js/app.js
     </body>
</html>

<!– App.js–>

var myapp = angular.module(“understandMe”,[]);
myapp.directive(“country”,function(){
           return {
                            restrict : ‘EA’,
                            template : “

Hello {{mycountry}} is my country

“+
                                                    ‘<states></states>’,
                            link : {
                            pre: function(scope,element,attr) {
                                          scope.mycountry = “India”
                                   }
                        }

                }
            })

myapp.directive(“states”, function() {
                         return {
                                        restrict :’EA’,
                                       template : “

{{state}} state

“,
                                        link: function(scope,element,attr) {
                                      scope.state = scope.mycountry +” ” + “has a” +” ” + “Kerala”;
                                    }
                        }

             })

You can see there are two directives created. country and states. Here I am sharing data from country directive to states also including states directive inside the country.

So what’s special here. ??!!!

You can see very  small difference inside the country directive I have used a “pre” link function!!!!. Why is that ????!!!

There is  Directive execution  order come in the picture. If you write only  link function in both directives then you will be not able to get the data from parent directive to child directive.

In Angular, link function is divided in to two parts  pre link and post link. Normal link functions same as post link which execute at last. pre link will executes first.  But if both the link functions are post link then child directive function will execute first.

Introducing reduce method.

reduce method reduces your array to single value.

How to use reduce method ?

Syntax : array.reduce(function(initalValue,currentValue,index,arr),initalValue)

reduce method has two parameters. One is a call back function which is required parameter and an optional parameter initalValue.

Call back function has two required parameters, they  are initalValue and currentValue. Other two parameters are optional.

Example : var myArray = [20,30,10,40,50];

Find out the sum of the myArray elements ? 

Here the solution with reduce method.

myArray.reduce(function(f,c){ return f+c},0)

here the above code f is the initial value and c is the current value.

Output : 150

A Custom Angular js Directive for Github user information.

To see the complete code please visit my github account

https://github.com/pvkrijesh/githubDirective/

 

//HTML

<html ng-app=”myGithub”>
      <title>Github directive</title>
      <head>
            script src=” http://lib/angular.min.js
            script src=” http://github.js
         </head>
   <body>

<git-profile user-name=”‘pvkrijesh'”></git-profile>
     </body>
</html>

//JS (github.js)

/** Name : Angular Github Userinfo Directive
* Description: A Simple Github Directive in Angular JS.
* Author : Krijesh PV.
* Email :pvkrijesh@gmail.com
**/
(function() {

//Module Init
var myApp = angular.module(“myGithub”,[]);
//Directive decalration
myApp.directive(‘gitProfile’, [‘$http’, function($http) {
        return {
                     restrict: ‘E’,
                     transclude: true,
                     replace: true,
                    scope:  {
                                 userName:’=’,
                                },

                   controller:function($scope)  {
                                var commongitUrl = “https://api.github.com/users/
                                var userapiUrl = (commongitUrl +$scope.userName);

                                $http({method: ‘GET’, url:userapiUrl}).then(function (result) {
                                        $scope.avatarurl = result.data.avatar_url;
                                       $scope.avatarlogin = result.data.login;
                                       $scope.avatarfollowers = result.data.followers;
                                      $scope.avatarfollowing = result.data.following;

                                     }, function (result) {
                                    alert(“Error: Empty Response”);
                             });
                 },

template: div  style=’border:solid 2px; width:300px’> <img style=’margin-left:40px;margin-top:40px’ ng-src='{{avatarurl}}’></img><h6 style=’margin-left:100px;’>{{avatarlogin}}</h6> <span>Followers :{{avatarfollowers}}  Following :{{avatarfollowing }}</span></div>,

}

}]);

}());

Expected OUTPUT:

output

JavaScript Interview Questions

js

1. function myFn () {

     var a=b=c=10;  
    }
myFn();
console.log(a) ?
console.log(b)?
console.log(c)?

Ans:  console.log(a) will print  “a is not defined” // var a is defined inside the function with var keyword. It is a local variable and not able to access out side the function.

console.log(b) will print 10 //b declared with out var keyword so it is a global variable.

console.log(c) will print 10//c eclared with out var keyword so it is a global variable.

—————————————————————————————————————————————–

2. var myVar =”krijesh”;

         myAnotherVar = “pv”

        delete myVar;

        delete myAnotherVar;

        console.log(myVar)?

       console.log(myAnotherVar)?

Ans: console.log(myVar) will print “krijesh”

console.log (myAnotherVar) will print “not defined”

—————————————————————————————————————————————–

3.  var myArray = [1,2,3]

      newArray = myArray;

     myArray.push(4);

    console.log(newArray) ?

Ans: console.log(newArray) will print [1,2,3,4]

—————————————————————————————————————————————–

4. print the below pattern using javascript

       *****

       ****-

       ***–

       **—

       *—-

Ans: str =””;
n=5;
for(i=n;i>0;i–) {

for(j=0;j<n;j++) {

if(j<i){

document.write(“*”)

}
else {
document.write(“-“)

}

}
document.write(“<br/>”)
}

—————————————————————————————————————————————–

5. Check the number is integer or float in JavaScript?

Ans : var myInput = 100;

if(myInput ===parseInt(myInput ,10)){

alert(myInput  + “is a Number”) //code will alert 100 is a Number

}
else if(myInput ===parseFloat(myInput ,10)){

alert(myInput + “is a Float”)

}
else {

alert(“Neither Integer Nor Float”)
}

—————————————————————————————————————————————–

6.var myArray =[1,2,3,4]  add  ‘_’ to each element with out using any for loop in JavaScript.?

expected output : myArray=[1_,2_,3_,4_]

Ans:  var newArray =myArray.map(function(e) { return e+”_”} );

—————————————————————————————————————————————–

7. Find the Output difference from below functions.

    a) function myFun () {

         var a = 10;

          console.log(this.a)

       }

     b) function myAnotherFun(a) {

           this.a =10;

           console.log(this.a)

        }

    myFun();

   myAnotherFun();

Ans:  First function gives you the output undefined. because a is local variable and this refer to window object.

second function gives you the output 10. “this” will refer the function context and print the value of a  


8. Write a function to check the given input is an object,string or array in JavaScript ?

Ans:   function typeCheck(input)  {

if(typeof(input)===’object’)  {
console.log(“Input is an object”)

} else if(typeof(input)===’string’) {

console.log(“Input is a string”)

}  if(input instanceof Array)  {

console.log(“Input is an array”)

}

}

typeCheck(“krijesh”);
typeCheck({name:”krijesh”})


9. What is the output console.log(3<2<1) ?

Ans: true. //First check goes to 3 < 2 it will give you false. Next check false < 1 it means 0 < 1 gives you true.


10. Write a JavaScript program to find a factorial of  number. ?

Ans:        function fact (numb)  {

var fact =1;
for (i=1;i<=numb;i++) {

fact = fact*i

}
return fact;
}


11.  var obj = new Object();

        var foo = new Object();

         var bar = new Object();

        obj[foo] = ‘krijesh’

          obj[bar] = “pv”

        console.log obj[foo] ?

Ans : It prints you the output  “pv”.

Why ?

In JavaScript always object key should be string. In the above case when you assign obj[foo] = ‘krijesh’ then your obj structure will be obj { [object Object] : “krijesh”};

Next time again you are assigning obj[bar] = “pv” now also your object structure will be  obj{[object Object] : “pv”} So here the object keys are same every time you assign a new value it will over ride.


12. var  foo = 10;

       function helloWorld() {
             foo = 20;

            function foo() {}
 }

helloWorld();

console.log(foo)?

Ans: foo will print 10.

Why ?

var foo =10 //declares globally.

next helloWorld function which has a function ‘foo‘ it will hoist at the top of the function.

So it will be 

function helloWorld() {
var foo = function() {}
foo =20
}

after hoisting foo became the local variable of the helloWorld function. Next it gets override with the value 20.

Introducing test & exec method in Javascript RegEx

exec () method search the input string , if the string matches it returns an array else returns a null.

Ex:    var myInputString=”Hello I am Krijesh”;
var check = new RegExp(“l”);
check.exec(myInputString);
output:[“l”]

The test() method tests for a match in a string.

This method returns true if it finds a match, otherwise it returns false.

Ex:    var str = “hello world!”;
var result = /^hello/.test(str);
console.log(result) //return true

To Do Tasks in Angular JS

<!DOCTYPE html>
<!– This is a simple Todo tasks in Angular JS
Author – Krijesh PV.
–>
<html>
<head>
<title>Kriz Angular</title>
<script src= “http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script&gt;
<script>
/*
** module initialization
*/
var myApp = angular.module(“app”,[]);
myApp.controller(“firstCtrl”,function($scope){

/*
**add Tasks
** @Param tasks.
*/
$scope.myTasks= [];
$scope.addTasks = function(tasks){
$scope.myTasks.push(tasks);
}

/*
**Clear Tasks
** @Param tasks.
*/
$scope.clearTasks =function(tasks){
$scope.myTasks.length=0;
}
})
</script>
</head>
<body ng-app=”app”>
<div ng-controller=”firstCtrl” style=”border:2px solid #E75D5C; padding:5px;”>
<input type=”text” name=”tasks” ng-model=”tasks”>
<button ng-click=”addTasks(tasks)”>Add Tasks</button>
<button ng-click=”clearTasks(tasks)”>Clear Tasks</button>
<ul ng-repeat=”myTask in myTasks track by $index”>
<li>
{{myTask}}
</li>
</ul>
</div>
</body>
</html>