- Immutable JavaScript library is created by Facebook developers.
- In this demo, “We will learn about Immutable JavaScript library with a Map example”.
- Immutable data does not change once created.It means a new immutable object is created if any changes are done.
- You can find more information about Immutable library using following link:-
http://facebook.github.io/immutable-js/
- Immutable library provides List, Stack, Map, OrderedMap, Set, OrderedSet and Record.
- To demonstrate the immutable we have created a AngularJS application with a controller name MyController.This controller contains a immutable map containing fruit names.In the demo.html file fruit names are rendered using a unordered list.
- The following screenshot shows the directory structure of this demo:-
- AngularJS can be installed using npm install angular --save command.The following screenshot shows the terminal with Angular 1.4 installation.
- ImmutableJS can be installed using npm install immutable --save command.The following screenshot shows the terminal with Immutable js installation.
- The code content of demo.html file are as follows:-
<!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>ImmutableJS Demo</title> <script src="node_modules/immutable/dist/immutable.min.js"></script> <script src="node_modules/angular/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-controller="MyController"> <h1>List of Fruits:-</h1> <ul> <li ng-repeat="aFruit in fruitsMap.toArray()"> {{aFruit}} </li> </ul> </body> </html>
- The code content of app.js file are as follows:-
var myApp = angular.module("myApp",[]); myApp.controller("MyController", function($scope){ $scope.fruitsMap = Immutable.Map({ 1:"Apple", 2:"Orange" }); $scope.fruitsMap = $scope.fruitsMap.set(3, "Grapes"); });
- The output of the demo looks like following screenshot with all fruit names are listed using unordered list.
- The demo code can be downloaded from the following link:-