Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


Building ReactJS Example with Event Handling

Posted on

Here is another simple example of ReactJS in which bunch of CommentBox components has been created and wrapped into a Board layer which is also a React Component and therefore events are binding to Save & Edit button under CommentBox component.

Set of comments text is initialized in parent Component i.e Board and each comment text is getting rendered into CommentBox Component by iteration.

Here is complete code:-

                <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <title></title>
        </head>

        <body>
            <div id="content"></div>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
            
            <script type="text/babel">

                class CommentBox extends React.Component{
                constructor(props){
                    super(props);
                    this.state = {
                    editable : false
                    };
                }

                save(event){
                    this.props.updateCommentText(this.refs.commentTxt.value,this.props.index);
                    this.setState({
                        editable:false
                    })
                }
                remove(){
                    this.props.removeCommentText(this.props.index);
                    
                }
                edit(){
                    this.setState({
                        editable:true
                    })
                }
                renderForm(){
                    return (
                    <div className="row">
                        <div><textArea ref="commentTxt" name="commentBox" defaultValue={this.props.children}></textArea></div>
                        <button type="button" className="btn btn-danger" onClick={this.save.bind(this)}>Save</button>
                    </div>
                    );
                }
                renderHtml(){  
                    return (
                        <div className="row">
                        <div>{this.props.children}</div>    
                        <button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
                        <button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
                        </div>
                    );
                }

                render() {
                    if(this.state.editable){
                        return this.renderForm(this);
                    }else{
                        return this.renderHtml(this);
                    }
                }
                }

            class Board extends React.Component{
                constructor(props){
                    super(props);
                    this.state ={
                        comments:[
                            'Techical Comments',
                            'Wordpress Comments',
                            'Facebook Comments'
                        ]
                    }
                }
                updateComment(text,i){
                    console.log("Saving Comment..."+text+" index ["+i+"]")
                    var arr = this.state.comments;
                    arr[i] = text;
                    this.setState({comments:arr})
                }
                removeComment(i){
                    console.log("Removing Comment..." + "index ["+i+"]")
                    var arr = this.state.comments;
                    arr.splice(i,1);
                    console.log("After removing a record :"+arr)
                    this.setState({comments:arr});
                }    

                eachComment(text,i){
                    return (
                                <CommentBox key={i} index={i} updateCommentText={this.updateComment.bind(this)}  removeCommentText={this.removeComment.bind(this)}> {text}</CommentBox> 
                            );
                }

                render(){
                    return(
                        <div className="container-fluid">{
                        this.state.comments.map(this.eachComment.bind(this))
                        }
                        </div>
                    );
                }
            } 
            ReactDOM.render(
                <Board />
                , document.getElementById('content'))
            </script>
        </body>

        </html>

Building First ReactJS Example

Posted on Updated on

 

 

Below is sample example of ReactJS in which a counter variable is an increment or decrement by 1 on onClick event that is binding with a button.

Here is a complete example.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title></title>
  </head>
  <body>
    <div id="content"></div>

    <script src="https://fb.me/react-0.14.7.js"></script>
    <script src="https://fb.me/react-dom-0.14.7.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
    
    
    <script type="text/babel">

        class CounterValue extends React.Component{
        constructor(props){
            super(props);
            this.state = {
            counter : 0
            };
        }

        onIncrementClickHandler() {
            this.setState({counter:this.state.counter +1})
        }

        onDecrementClickHandler() {
            if(this.state.counter == 0 ){
                return;
            }else{
             this.setState({counter:this.state.counter -1})
            }
        }
        render() {
            return (
            <div>
                <input type="button" onClick={this.onIncrementClickHandler.bind(this)} value="Increment"/>
                <input type="button" onClick={this.onDecrementClickHandler.bind(this)} value="Declement"/>
                <div>Counter value is  : {this.state.counter}</div>
                </div>
            );
        }
        }

      ReactDOM.render(<CounterValue />, document.getElementById('content'))
    </script>
  </body>
</html>

Command Design Pattern

Posted on Updated on

Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

  1.  Decouple the caller and receiver call so the caller doesn’t know about receiver or receiver doesn’t know about a caller, they are communicating with Command layer.
  2. Allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests.
  3. delegates a request to a command object instead of implementing a particular request directly.

Key Points:-

Client – creates a ConcreteCommand object and sets its receiver.
Invoker – Asks the command to carry out the request;
Command – it is performing as “tokens” that are created by one client that knows what need to be done and passed to another client that has the resources for doing it.
Receiver –  knows how to perform the operations;

Below is snippet code for Command Design Pattern.

Command.Java – Here, Command decouples the object that invokes the operation from the one that knows how to perform it

package com.design.db;

public interface Command {
    Task submit();
}

DBSaveCommand.Java

package com.design.db;

public class DBSaveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBSaveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.save(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Save");
    }
}


DBRemoveCommand.Java

package com.design.db;

public class DBRemoveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBRemoveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.remove(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Delete");
    }
}


DBFetchByIdCommand.Java

package com.design.db;

public class DBFetchByIdCommand implements Command {

    private final Long toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchByIdCommand(Class<?> persistCollection, Long object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchById(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

DBFetchAllCommand.Java

package com.design.db;

public class DBFetchAllCommand implements Command {
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchAllCommand(Class<?> persistCollection) {
        this.persistCollection = persistCollection;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchAll(this.persistCollection);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

Receiver.Java

package com.design.db;

import java.util.Collection;

public interface Receiver {

    void save(Class<?> persistCollection, Object object);

    void remove(Class<?> persistCollection, Object object);

    Object fetchById(Class<?> persistCollection, Long id);

    Collection<?> fetchAll(Class<?> persistCollection);
}



DBRequestProcessor.Java – All the operation are perform here and only Command knows about the receiver and invokes the method of a receiver that is passed on through parameters.

package com.design.db;

import java.util.Collection;
import java.util.Collections;

public class DBRequestProcessor implements Receiver {


    @Override
    public void save(Class<?> persistCollection, Object object) {
        System.out.println("Entity Save");
    }

    @Override
    public void remove(Class<?> persistCollection, Object object) {
        System.out.println("Entity Removed");
    }

    @Override
    public Object fetchById(Class<?> persistCollection, Long id) {
        return id;
    }

    @Override
    public Collection fetchAll(Class<?> persistCollection) {
        return Collections.EMPTY_LIST;
    }
}

Invoker.Java

package com.design.db;

public interface Invoker {
    Task invoke(Command command);
}


DBCommandInvoker.Java – Invoker only know how to execute the Command and unknown about their concrete implementation of Command Interface.

package com.design.db;

public class DBCommandInvoker implements Invoker {


    public DBCommandInvoker() {
    }

    @Override
    public Task invoke(Command command) {
        return command.submit();
    }
}

Task.Java

package com.design.db;

public interface Task<T> {
    T get();
}


SqlRepository.Java :- This is Client here, which decides which command to be executed. to execute the Command, it passes to invoker object i.e DBCommandInvoker.

package com.design.db;

import java.util.Collection;

public class SqlRepository {

    private Invoker dbCommandInvoker = new DBCommandInvoker();

    public void save(Class zlass, Object payload) {
        dbCommandInvoker.invoke(new DBSaveCommand(zlass, payload));
    }

    public void remove(Class zlass, Long id) {
        dbCommandInvoker.invoke(new DBRemoveCommand(zlass, id));
    }

    public Object fetchById(Class zlass, Long id) {
        return dbCommandInvoker.invoke(new DBFetchByIdCommand(zlass, id)).get();
    }

    public Collection fetchAll(Class zclass) {
        return (Collection) dbCommandInvoker.invoke(new DBFetchAllCommand(zclass)).get();
    }
}


Setup React JS with NodeJS and Visual Studio Code

Posted on Updated on

Before getting started with first React JS example, download Visual Studio Code Editor that help you configure and better guidance of developing a React JS application.

Download & Install Visual Studio Code from here.
Download and install Node.Js from here.

Once the installation is done then create a root folder where do you want to set up a React JS Project.

>>cd d:
>>mkdir React
>>cd React
>>npm install –g create-react-app
>>create-react-app my-first-app
>>cd my-first-app
>>npm start

Once all step’s done successfully then the my-first-app folder will be created in your root folder React, go inside this folder and you will see all dependencies JS and related configuration files will be placed here.

Next, Open Visual Studio Code and Open project from File-> Open Folder

 

Then open http://localhost:3000/ to see your app.

Sort Array of String by their counts in Java 8

Posted on

Here, we will see how to sort an array base on elements occurrences in Java 8.

Suppose we got a city list containing duplicate city as well like below.

"Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";

First, we have to do aggregation on city name by applying groupBy function, count their occurrence and return a Map.

 String cities = "Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";
        
 TreeMap<String, Long> groupByCitiesMap = Stream.of(cities.split(","))
                .collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
 System.out.println(groupByCitiesMap);

This will return a TreeMap of sorted by City (natural sorting) that containing unique city name as key and their counts as in value.

{Agra=3, Bihar=3, Delhi=5, Uttar Pradesh=2}

OR

We can do it old fashion without using Stream.

TreeMap<String, CityReport> treeMap = new TreeMap();
for (String city : cities.split(",")) {
    CityReport cityReport = new CityReport(city);
    if (treeMap.containsKey(city)) {
        treeMap.computeIfPresent(city, (key, val) -> {val.counter+=1;return val;});
    } else {
        treeMap.put(city, cityReport);
    }
}

This will return a Map that containing unique city name as key and CityReport as value containing city name and count.

{Agra=CityReport{city=’Agra’, counter=3}, Bihar=CityReport{city=’Bihar’, counter=3}, Delhi=CityReport{city=’Delhi’, counter=5}, UP=CityReport{city=’UP’, counter=2}}

and Finally, need to be sorted out by City count and City name. so here we do so…

List<CityReport> sortedCityReport = treeMap.values().stream().sorted(new ComparatorFilter(new ComparatorByNumber(),new ComparatorByName())).collect(Collectors.toList());

System.out.println("Sort By Count first then City Name "+ sortedCityReport);

Output:

Sort By Count first then City Name [CityReport{city=’UP’, counter=2}, CityReport{city=’Agra’, counter=3}, CityReport{city=’Bihar’, counter=3}, CityReport{city=’Delhi’, counter=5}]

Rest of code is below:-

ComparatorFilter.Java :- Sorting by chain of comparator ( by count and name )  over the Collection.

static class ComparatorFilter implements Comparator<CityReport> {

    private final List<Comparator<CityReport>> comparators;

    ComparatorFilter(Comparator<CityReport>... comparators) {
        this.comparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(CityReport o1, CityReport o2) {
        for (Comparator c : this.comparators) {
            int val = c.compare(o1, o2);
            if (val != 0) {
                return val;
            }
        }
        return 0;
    }
}

ComparatorByName.Java – Sorting by City Name

static class ComparatorByName implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return o1.city.compareTo(o2.city);
    }
}

ComparatorByNumber.Java – sorting by count number.

static class ComparatorByNumber implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return (int) (o1.counter - o2.counter);
    }
}

CityReport Model Class –


class CityReport {
String city;
Long counter;

public CityReport(String city) {
    this.city = city;
    this.counter = 1L;
}


@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CityReport that = (CityReport) o;
    return Objects.equals(city, that.city);
}

@Override
public int hashCode() {

    return Objects.hash(city);
}

@Override
public String toString() {
    return "CityReport{" +
            "city='" + city + '\'' +
            ", counter=" + counter +
            '}';
}
}

Angular Filter

Posted on Updated on

 

 

 

 

What is Filter in AngularJS?

Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters as given below, but it is easy to define your own as well.

The general syntax in templates is as follows:

{{ expression [| filter_name[:parameter_value] ... ] }}

Build-in AngularJS filter

Name Description
filter Selects a subset of items from array and returns it as a new array.
currency Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number Formats a number as text.
date Formats date to a string based on the requested format.
json Allows you to convert a JavaScript object into JSON string.
lowercase Converts string to lowercase.
uppercase Converts string to uppercase.
limitTo Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, it is converted to a string.
orderBy Returns an array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.

Currency Filter Example :-

In HTML Template Binding
{{ currency_expression | currency : symbol : fractionSize}}
In JavaScript
$filter('currency')(amount, symbol, fractionSize)
Snippet example here:-



Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{1234.1324 | currency : "USD$" :4}}

Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
<hr/>		


Date filter example :

In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
Snippet example here:-


 Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
 
 Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
 
 Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
 <hr/> 


Number filter example :

In HTML Template Binding
{{ number_expression | number : fractionSize}}
In JavaScript
$filter('number')(number, fractionSize)
Snippet example here:-
Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}

Json filter example :

In HTML Template Binding
{{ json_expression | json : spacing}}
In JavaScript
$filter('json')(object, spacing)
Snippet example here:-


 JSON : {{JSONValue}} Filter : {{JSONValue | json}}
 
 JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
 <hr/> 


Uppercase and Lowercase filter example :

In HTML Template Binding
{{ lowercase_expression | lowercase}}
{{ uppercase_expression | uppercase}}
In JavaScript
$filter('lowercase')()
$filter('uppercase')()
Snippet example here:-


 Name Value is {{name}}
 
 Upper Case : {{name | uppercase}}
 
 Lower Case : {{name | lowercase}}
 <hr/> 


 filter example :

In HTML Template Binding
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
In JavaScript
$filter('filter')(array, expression, comparator, anyPropertyKey)
Snippet example here:-
<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>

How to Create custom filter?

Writing your own filter is very easy: just register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.

angular.module("myApp",[]).filter('reverse', function() {
 return function(input, uppercase) {
 input = input || '';
 var out = '';
 for (var i = 0; i < input.length; i++) {
 out = input.charAt(i) + out;
 }
 // conditional based on optional argument
 if (uppercase) {
 out = out.toUpperCase();
 }
 return out;
 };
})</pre>

HTML binding here



<pre>

<div>
 <input ng-model="greeting" type="text">
 No filter: {{greeting}}
 Reverse: {{greeting|reverse}}
 Reverse + uppercase: {{greeting|reverse:true}}
 Reverse, filtered in controller: {{filteredGreeting}}
</div>


Complete Example here :-

<html ng-app="myApp">
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-controller="filterController">
	<h1> Angular Build-in Filter Example </h1>
	<hr/>
	<p>
		Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{currencyValue | currency : "USD$" :4}}
		<br/>
		Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
		<hr/>	
	</p>	

<p>
	Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
	<br/>
	Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
	<br/>
	Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
	<hr/>	
</p>

<p>
	Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}
	<hr/>	
</p>

<p>
	JSON : {{JSONValue}} Filter  : {{JSONValue | json}}
	<br/>
	JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
	<hr/>	
</p>

<p>
	Name Value is {{name}}
	<br/>
	Upper Case   : {{name | uppercase}}
	<br/>
	Lower Case   : {{name | lowercase}}
	<hr/>	
</p>

<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>
<p>
<input ng-model="greeting" type="text"><br>
  No filter: {{greeting}}<br>
  Reverse: {{greeting|reverse}}<br>
  Reverse + uppercase: {{greeting|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredGreeting}}<br>
</p>
</body>
<script type="text/javascript">
angular.module("myApp",[])
.controller("filterController",function($scope){
	$scope.todayDate = new Date();
	$scope.dateInTimestamp = $scope.todayDate.getTime();
	$scope.currencyValue = 1234.33;
	$scope.numberValue = 123.456789;
	$scope.JSONValue = "[{'key':'value'}]";
	$scope.name="Sample Angular Filter Example";
	$scope.listOfItem = [
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
})
.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = '';
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
</script>

</html>




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.

 

AngularJS + RequireJS Example

Posted on Updated on

Prerequisite Dependency Javascripts Path –

You can download dependencies script files from below path.

Project Structure:-

 

 

 

 

 

 

 

 

index.html

HTML page for the arithmetic operation.

 

app.js

This is requireJS configuration file, so we defined all dependencies and javascript path.


requirejs.config({
	baseUrl: './scripts',
    shim : {
        angular: {
            exports : 'angular'
           },
        app:{
            deps:['angular','jquery']
        }

    },
    paths: {
        "angular" : "./../lib/angular.min",
        "bootstrap" :  "/../lib/bootstrap.min",
        "jquery":"./../lib/jquery-3.2.1.min",
        "main":"./../main"  
    }
});

requirejs(['main']);

main.js

In this file, we can add all components of AngularJS like Services, Controllers, Directive and Utility files. Since we are only using Controller file in this example so only Controller file is getting added into angular.module(…).


define(['RegisterControllers','angular'],function (RegisterControllers,angular) {

  angular.module('myApp', ['ui.controllers']);
  angular.bootstrap(document, ['myApp']);

});

Controllers/PrimaryController.js

In this Controller file, methods are defined which handle action on button clicked.


define(['angular'],
	function (angular) {

		var myCtrl = null;
		PrimaryController = function($scope){
			this.$scope = $scope;
			this.$scope.myCtrl = this;		
			this.init();
		}
		PrimaryController.$inject=["$scope"];

		PrimaryController.prototype ={
			init : function(){
        	this.$scope.message = "Hellow How are you";
        },
           doAction : function(){
           	var num1 = this.$scope.number1;
			var num2 = this.$scope.number2;

			this.$scope.result = parseInt(num1) + parseInt(num2);
           }
        
        };

		return PrimaryController;

	});

RegisterController.js –

Here, we register a Controller into angular.module(“ui.controllers”,[]). Also you can pass multiple controllers file path seperated by comma and assign into variables in function body then add all of them one by one in angular.module(…).controller(…).controller(..).

 


define(['./controllers/PrimaryController','angular'],
	function (PrimaryController,angular) {

    return angular.module("ui.controllers",[])
    	.controller("PrimaryController",PrimaryController);
});

Finally open index.html page in your browser, we will see the below output.

Download complete code here.

Thanks!!

What is requireJS

Posted on Updated on

What is RequireJS?

Modular Programming is used to break a large application into smaller blocks of manageable code which are always easy to maintain, readable and reusable, But it’s high cost of managing the dependencies between modules are always a major concern of developers face throughout the application development process.

So RequireJS is one of the most popular Javascript API to manage dependencies between modules and it supports AMD ( Asynchronous Module Definition  ) approach to load the modules and resolved their dependencies.

Benefits of RequireJS.

  • Easy to use and maintain than traditional ways of developing a web application.
  • Minimize the code repetition, Block of code can be easy to reused between the modules.
  • Hassle free of maintaining and keeping the scripts file in correct order.
  • Lazy loading ( Only load what you need, on demand and asynchronously )

Let’s check, how to use RequireJs

Project Hierarchy

 

 

 

 

 

 

Define an Entry point of RequireJS

First, download the latest requirejs library from here and keep it inside lib folder. Now we need to define a html file and could named index.html where RequireJS is loading as shown below.

Here, data-main is a meta attribute for requireJs that defines the initialization point of the application. it’s defined a relative path for the file where to load the RequireJS configuration.

RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing “.js” suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path.

 

Configure RequireJS

In the file app.js we defined the RequireJS config options and all files are locate under baseUrl, Since baseUrl is a current directory in this demo example but You can define the baseUrl in your application where all scripts files are placed.

How to create modules

Three modules are defined here;

message.js

print.js

aboutus.js

Execute code RequireJS

Once, modules are defined then need to inject the dependencies and call the function.

main.js

Result

We can see the output in the web console.

 

 

 

 

See next example of Angular+RequireJS

Hope you like it. Thanks