What is Directive in AngularJS?

Posted on Updated on

What is Directive in AngularJS?

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope in Directive in AngularJS?

Unlike the other MVC frameworks, AngularJS doesn’t have specific classes or functions to create model objects. Instead, AngularJS extended the raw JavaScript objects with custom methods and properties. These objects, also known as scope in AngularJS terms, work as a glue between the view and other parts ( directives, controllers and services ) inside the AngularJS application.

Whenever the AngularJS application is bootstrapped, a rootScope object is created. Each scope created by controllers, directives and services are prototypically inherited from rootScope. AngularJS documentation is one of the best resources to learn how scope inheritance works: see Scopes in AngularJS. Understanding how scope inheritance works will be useful in following sections.

Directive Types:

You can implement the following types of directives:

The restrict option is typically set to:

  • 'A' – only matches attribute name
  • 'E' – only matches element name ( by Default )
  • 'C' – only matches class name
  • 'M' – only matches comment

These restrictions can all be combined as needed:

  • 'AEC' – matches either attribute or element or class name


Link – Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile – Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

Scope inside a directive

All directives have a scope associated with them. They use this scope for accessing data/methods inside the template and link function. By default, unless explicitly set, directives don’t create their own scope. Therefore, directives use their parent scope ( usually a controller ) as their own.

However, AngularJS allows us to change the default scope of directives by passing a configuration object known as directive definition object. A directive definition object –– let’s call it as DDO –– is a simple JavaScript object used for configuring the directive’s behaviour,template..etc. Check out AngularJS docs about DDO.

scope values can be either “false”“true” or “{}” in AngularJS directive.

Different types of directive scopes

Scope : False ( Directive uses its parent scope )

There will be no scope created in DDO therefore Directive use it parent scope. Any change made on the directive scope will be reflected in parent scope and vice versa. Both Controller and Directive scope will be in sync.

Scope : true ( Directive get new  scope )

it gets its own scope by setting up scope equals to true and assigned to directive.  This newly created scope object is prototypically inherited from its parent scope ( the controller scope where it’s been used ).

Let’s see difference between setting two  scope:false and scope:true

  • When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrtroller ( the parent scope ) will be reflected in the directive scope.
  • When scope is set to “false”, the controller Controller and directive are using the same scope object. This means any changes to the controller or directive will be in sync.

Scope : { } ( Directive gets a new isolated scope )

Till now, we saw two situations for directive scope creation. In the third type, we are going to set scope property in DDO to an Object literal. When an object literal is passed to the scope property, things are bit different. This time, there will be a new scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.

  • It’ll make sure that our directive is generic, and placed anywhere inside the application. Parent scope is not going to interfere with the directive scope.

Though it’s called as an Isolated scope, AngularJS allows to communicate with the parent scope using some special symbols knows as prefixes. Because of course there are still situations where the directive needs to be able to exchange data with parent scope. The next section is dedicated to Isolated scope and its properties.

There’re 3 types of prefixes AngularJS provides.

  1.  “@” ( Text binding / one-way binding )
  2.  “=” ( Direct model binding / two-way binding )
  3.  “&” ( Behaviour binding / Method binding )
  1. The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.
  2. Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.
  3. Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a method binding. This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.



Create a new Groovy project using maven

Posted on Updated on

This is a first exercise of writing a groovy program in IntelliJ IDE. See the first post of What is Groovy here?

Below is the complete example of Groovy using maven setup.

  • Create a folder as Project name i.e GroovyExample in your project folder.
  • Create an XML ( pom.xml )file under GroovyExample folder and named it as pom.xml.
  • Copy and paste the content of pom.xml as given inline below.
  • Open IntelliJ IDE and Click on File-> Open and select pom.xml file under GroovyExample folder by navigating it through.
  •  While importing all dependencies in given pom.xml into your project then you can start writing Groovy program.
  • Right click on Project and Create a directory i.e /src/main/groovy under which all groovy file will be placed.
  • Next, Select /groovy folder and right-click to create a new Groovy file.
  • Give proper groovy file name and click OK.
  • A Groovy file will be open then continue with Groovy code as given.

Maven POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <description>Demo project for Groovy Example</description>



Groovy file here :-


What is Groovy?

Posted on Updated on


What is Groovy?

Groovy is an optionally Typed, Dynamically language that runs on JVM. It is tightly integrated with the Java Language and its feature is enabled as rich and  Java friendly.

Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and lambda expression.

Groovy source code is compiled into Java byte-code by the Groovy compiler. To run Groovy code in a Java virtual machine, only the Groovy JAR file must be present in the classpath at runtime.

A Groovy source files ends with the .groovy extension. This file can contain a Groovy script or a Groovy class.

Compatibility with Java

Groovy runs on the JVM and can use Java libraries. Every Groovy type is a subclass ofjava.lang.Object.

Groovy does currently not support Java 8 lambda expressions.

Reasons to use Groovy

Groovy focus on simplicity and very productive.

  • Simplification : – Groovy does not require a semicolon to terminate the line. return type can be omitted, by default Groovy return the last expression of the line as return type. public keyword can be omitted, it is a Default in Groovy, Also it allows optional typing.
  • Ease of use – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.
  • Flexibility – Groovy allows to change classes and methods at runtime, e.g. if a method is called which does not exist on a class, the class can intercept this call and react to it. This allows for example that Groovy provides a very flexible builder pattern.
  • Easy to use : – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.

Setup Groovy in IntelliJ:-

Steps to follow to install Groovy in you IntelliJ.

  • Open IntellJ IDE.
  • Go to File->Settings -> plugin
  •  Choose Groovy in plugin Text box and install.
  • Once Groovy get installed in your IDE, then you will able to create a Groovy file and run it.
  • groovy-setup


Exercise :-


JSON Schema Validation example in java

Posted on

Validating input is a good programming practice than spending times to trying to guard each line of codes against all the way the input goes wrong.

This is especially true when we are writing a web service that deal with input data of a PUT,POST,DELETE and GET method with MIME type JavaScript Object Notation (JSON) .  JSON data is formatted as a key & value pair and each key & value represent a properties name and value separated by the colon (:).

In last post, we have seen the Jackson framework that is used to marshaling and unmarshalling the JSON data to Java object and vice-versa, But validating JSON data is another task, unfortunately Jackson framework does not  provide to do validate JSON data.

json-schema-validator available at https://github.com is quite popular with Java developer to validate JSON data against Schema file.

JSON schema is:

  • A way of describing your existing data format
  • Written in clear, human and machine readable, documentation
  • Complete structural validation useful for
    • Automated testing
    • Validating client submitted data

Look at the below Schema file. This schema file exactly tells, in Input JSON data , “id” must be String type, “amount” properties must be any Number type and “Currency” must be out of four currency else throw validation exception. As you can created own Schema file base on the incoming input date.


trade-schema.json under /src/main/resources/schema folder

  "title": "Daily Trade Transaction",
  "description": "Daily Trade Transaction",
  "type": "object",
  "properties": {
      "enum":["INR", "HKD", "EUR", "USD"]

ref link:-
validate Schema online :-

Let’s build a simple Application :-

trade.json :- Input data store in a file.



JsonSchemaManager.Java : Used to validate all Java Object with specific Schema.

package com.example.utilities;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javafx.scene.input.KeyCode.J;

 * Created by MYPC on 7/17/2016.
public class JsonSchemaManager {
    private final JsonValidator validator = JsonSchemaFactory.byDefault().getValidator();
    private Map<Class<?>, JsonNode> jsonNodeMap = new HashMap<>();

    public void load(Class<?> className, String schema) throws IOException {
        JsonNode schemaFromDisk = JsonLoader.fromURL(this.getClass().getResource(schema));
        jsonNodeMap.put(className, schemaFromDisk);

    public void check(Class<?> className, JsonNode toBeValidate) {

        ProcessingReport report = null;
        try {
            report = validator.validate(jsonNodeMap.get(className), toBeValidate);
            if (!report.isSuccess()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(" Oops!! failed JSON validation ");
                List messages = Lists.newArrayList(report);

                for (int i = 0; i < messages.size(); i++) { stringBuilder.append("- "); stringBuilder.append(messages.get(i).toString()); stringBuilder.append((i == (messages.size()) - 1) ? "" : "\r"); } throw new RuntimeException(stringBuilder.toString()); } } catch (ProcessingException e) { throw new RuntimeJsonMappingException("ERROR -->" + e.toString());

Main Class that validate the JSON data.

package com.example;

import com.example.model.Transaction;
import com.example.service.CSVReader;
import com.example.utilities.JsonSchemaManager;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.List;

 * Created by MYPC on 7/18/2016.
public class JSONSchemaReaderApp {

    public static void main(String[] args) throws IOException {

        JsonSchemaManager jsonSchemaManager = new JsonSchemaManager();
        CSVReader csvReader = new CSVReader();
        // Load schema file from resource folder.
        jsonSchemaManager.load(Transaction.class, "/schema/trade-schema.json");
        // Load JSON data from file system and convert into JsonNode Object
        List lists = csvReader.load(Transaction.class, JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        for (int i = 0; i < lists.size(); i++) {
            //validate each JsonNode of Type Transaction to Schema file.
            jsonSchemaManager.check(Transaction.class, lists.get(i));

complete src download here


Difference between WHERE vs HAVING clause in SQL

Posted on Updated on

MySQLThis is frequently asked questions in Database interview , .Net interview and Java Interview. Developer should know the basic differences of these two clauses in SQL.

Where” clause is used for selection a row or set of rows from table, base on criteria like primary key or other column fields table rows get retrieved. It can be used in update, delete and select statement base on the criteria or more than one criteria.

Having” clause used with aggregate function that is work over Group by selection, Having clause always followed by Group by clause or it does not perform like where clause. It boosts the better performance by avoiding unnecessary column sorting and grouping

Aggregate Function below:- 

  • AVG() – Returns the average value
  • COUNT() – Returns the number of rows
  • FIRST() – Returns the first value
  • LAST() – Returns the last value
  • MAX() – Returns the largest value
  • MIN() – Returns the smallest value
  • SUM() – Returns the sum

Difference between WHERE vs HAVING

  1. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.
  2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
  3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.
  4. The WHERE clause is used in any DML form like Select, Update and Delete Query while Having clause can be only used with Select statement.
  5. The Where clause can be applied individual row while Having clause can be applied only a group of rows.

Note: Having and Where clause can not be used together.


SQL Interview Question

Posted on Updated on





Concatenate multiple row into a single row :


This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows:

GROUP_CONCAT([DISTINCT] expr [,expr …] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name …]] [SEPARATOR str_val])

mysql>SELECT NAME, reminder_date,STATUS FROM enquiry;











 Find nth largest Salary in Employee Table:-

Select all Employee rows by Salary descending order.

 mysql>SELECT * FROM employee ORDER BY salary DESC;






Fetch 4th largest salary holder Employee :-

syntax : 

select * from <table-name> t2 where ( n-1 ) = ( select count(distinct(<t2>.<column-name>)) from <table-name> t2 where t2.salary > t1.salary);

example :-

         mysql>SELECT * FROM employee e1
WHERE  (4-1) = ( SELECT COUNT(DISTINCT(e2.salary)) FROM employee e2 WHERE                                      e2.`salary` >   e1.`salary`)