Search

Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. In this article, we will learn about how we can use a MongoDB database with NodeJS.  But before do that, let’s delve a little into NodeJS. Getting started with NodeJS  So what is Node JS, and why do we use it? NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. Installing NodeJs Plugin for MongoDB:Follow these steps to install Node JS  Install NPM (Node Package Manager).  The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. Double-check that you have npm installed in your system by simply running this command in your terminal: $ npm -v[Text Wrapping Break]6.13.6  Install the Node from NodeJs Website >> NodeJS.   See the type of Operation system and download the version as per your platform compatibility.  Follow the installation guide as suggested by the installer.  Check the node version by running this command in your terminal  $ node -v[Text Wrapping Break]v8.11.4  If you have installed Node before NPM, you will probably need to update your NPM.   npm install npm@latest -g  Installing MongoDB Node.js Driver  The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   npm install mongodb   To see the list of current drivers installed in the system, run the following command:  npm list mongodb  If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. Using Node.JS to connect to MongoDB database   To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.Cluster? What is a cluster?     A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here.    Connecting MongoDB  Now that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! We will begin with Importing the Mongo Client as shown below: const {MongoClient} = require('mongodb');  To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. const uri = "mongodb+srv://<put-your-username>:<put-your-password>@<write-your-cluster-url>/test?retryWrites=true&w=majority";   Note: You need to update your password and username for the user. Now that we are ready with our URI, create an instance of MongoClient as below: const client = new MongoClient(URI);  Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  await client.connect();  We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  await listAllDatabases(client);  You can put any name to the above function. The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  And, close the connection as below:  finally { await client.close(); }  No, let’s put everything together and call our main function() as:  async function main(){ const uri = "mongodb+srv://<your-username>:<your-password>@<your-cluster-url>/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close(); }  Break]main().catch(console.error);  //To see if there are aby errorsLet’s use our function “listAllDatabases” to list all the databases in our cluster.  async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  (Ensure that the server is running and up!) node list.js  The output should come as below:  Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  Now that we are running with the database, let’s see the different data types they are supported on.  Mongo DB data types Have you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: String − It is used to store the data. It should be UTF-8 valid. Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. Boolean − To store a boolean (true/ false) value we use this type of data type. Double − Used for storing floating-point values. Arrays − This type of data-type is used for storing list or arrays. Timestamp - This type of data-type is used to check if an element has been modified or added. Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) Null − This type of data-type is used by MongoDB to store a Null value. Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. Object ID − Mongo uses this type of datatype to store the document’s ID. Binary data − Typically used to store binary data. Mongo DB and Collections  A database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  const collection = db.createCollection(name, options), or  const collection = db.collection(‘books’);     where, name is the connection name which can be anything, The option is a configuration document used for specifying the collection and is optional. We can list the following options while creating a collection: capped, autoIndexId, max, and size. createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. Note: In MongoDB, a collection is never created until it gets some content!  db.collection('check', {strict:true}, function(err, collection) {});    So, this code will never create a collection until and unless you specify and insert it in the document.  ConclusionToday we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  Happy Learning! :) 
Introduction to Mongo DB
KnowledgeHut

Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. In this article, we will learn about how we can use a MongoDB database with NodeJS.  But before do that, let’s delve a little into NodeJS. Getting started with NodeJS  So what is Node JS, and why do we use it? NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. Installing NodeJs Plugin for MongoDB:Follow these steps to install Node JS  Install NPM (Node Package Manager).  The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. Double-check that you have npm installed in your system by simply running this command in your terminal: $ npm -v[Text Wrapping Break]6.13.6  Install the Node from NodeJs Website >> NodeJS.   See the type of Operation system and download the version as per your platform compatibility.  Follow the installation guide as suggested by the installer.  Check the node version by running this command in your terminal  $ node -v[Text Wrapping Break]v8.11.4  If you have installed Node before NPM, you will probably need to update your NPM.   npm install npm@latest -g  Installing MongoDB Node.js Driver  The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   npm install mongodb   To see the list of current drivers installed in the system, run the following command:  npm list mongodb  If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. Using Node.JS to connect to MongoDB database   To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.Cluster? What is a cluster?     A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here.    Connecting MongoDB  Now that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! We will begin with Importing the Mongo Client as shown below: const {MongoClient} = require('mongodb');  To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. const uri = "mongodb+srv://:@/test?retryWrites=true&w=majority";   Note: You need to update your password and username for the user. Now that we are ready with our URI, create an instance of MongoClient as below: const client = new MongoClient(URI);  Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  await client.connect();  We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  await listAllDatabases(client);  You can put any name to the above function. The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  And, close the connection as below:  finally { await client.close(); }  No, let’s put everything together and call our main function() as:  async function main(){ const uri = "mongodb+srv://:@/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close(); }  Break]main().catch(console.error);  //To see if there are aby errorsLet’s use our function “listAllDatabases” to list all the databases in our cluster.  async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  (Ensure that the server is running and up!) node list.js  The output should come as below:  Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  Now that we are running with the database, let’s see the different data types they are supported on.  Mongo DB data types Have you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: String − It is used to store the data. It should be UTF-8 valid. Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. Boolean − To store a boolean (true/ false) value we use this type of data type. Double − Used for storing floating-point values. Arrays − This type of data-type is used for storing list or arrays. Timestamp - This type of data-type is used to check if an element has been modified or added. Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) Null − This type of data-type is used by MongoDB to store a Null value. Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. Object ID − Mongo uses this type of datatype to store the document’s ID. Binary data − Typically used to store binary data. Mongo DB and Collections  A database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  const collection = db.createCollection(name, options), or  const collection = db.collection(‘books’);     where, name is the connection name which can be anything, The option is a configuration document used for specifying the collection and is optional. We can list the following options while creating a collection: capped, autoIndexId, max, and size. createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. Note: In MongoDB, a collection is never created until it gets some content!  db.collection('check', {strict:true}, function(err, collection) {});    So, this code will never create a collection until and unless you specify and insert it in the document.  ConclusionToday we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  Happy Learning! :) 
10475
Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is use... Read More

What Is React-js State?

You must have already learned about the basic building block of any React application which is a Component.  A component represents a feature that may be made up of several smaller components. Components can be broadly classified into functional or class components.  Components may take in some values as properties (prop) to render a page. These props decide how to render a page. function Welcome(props) {   return < h1 >Hello, {props.name}; }In addition to props, a component can also have a state that holds a value that can keep a track of all the information within a component. In this article, we will focus mainly on what is State, how we can define and utilize State and how components can use it in data management.  Defining React StateSo what exactly is state? What is it used for?    State represents a component’s underlying data model and is rendered by the component. But more importantly, whenever data in the state changes, it causes the component to re-render to reflect the change. This facilitates declarative programming where you can simply manipulate state; while React takes care of implementing updates to ensure your component reflects the data in the State accurately.  In Class component we can use State as follows:  class Welcome extends React.Component {     constructor() {         super();         // Space To define the state         this.state = {            isDisabled: false,            totalCost: 0,            products: []         }     }     // To Define render method  } We can also use state in Functional components using the useState Hook. Hooks are a new addition in React 16.8 which let us use State and other React features in functional components.  When should I use a Hook?If you are writing a functional component and realize that you need to add a State to it, the only option previously was to convert it to a class. Now you can use a Hook inside the existing function component.  For this, you can directly read the React documentation of Hooks here. In this article, we will mainly focus on “what is a State” and how is it different from Props. Difference of Props and State Most of the developers who are new to React often think about when to use State and when to use a Prop. Let’s understand this dilemma with an example.   A React component is akin to a JavaScript function.  A State can only be utilized in class components natively and is quite similar to a Prop, with the only exception that it is fully private, which means it can only be fully controlled and accessed by a component. In functional components, you have to opt-in to the useState hook to include stateful features.  Props, on the other hand, allow you to reuse the component by giving it an ability to receive data as input from the parent component.   We will learn more about the State and its usage later in this article, but here is the practical difference between the two:  A fictional example of Using a State: class MyComponent extends React.Component {     state = {         name: 'Tom'  //defining the name property inside component state     }     render() {         return Hello {this.state.name};     }  }  Here, we can use the state ‘name’ anywhere in the component named “MyComponent” with the value ‘Tom’, or we can assign a new state also in the same component. And, Using a Prop:A Prop is a short name for properties. React is nothing without a Prop. Earlier we saw an example where we used the same data over and over again, but what if we have a scenario where we need the same component but not the same data? For example, I might want the theme component, but instead of a dark theme, I would like to use a light theme! What I mean here is that basically, I want to re-use “MyComponent” again, but not the data defined in it. This is where Props will come in useful; in cases when we want to change the content inside the reusable component.     class ThemeProvider extends React.Component {     render() {         return Current theme is {this.props.theme};     }    }  // when re-using the component with differnt data                It’s absolutely fine if you are not familiar with this code snippet. The idea is to understand when to use state or prop, and not the code as of now!  For now, just know that Prop is just a state, which is passed from parent to child. And because props can’t change their value in the child component, they take the help of an event listener or callback function in the parent component.    Now let’s quickly jump into the basics of a State.    Creating the State Object  React component has a built-in state object. Before you think that state is a very simple concept, let me stop you right there!  It’s not!  You should not forget the data flow in React! In React there is a uni-direction flow of data, which is from parent to child. This can be a bit confusing, in that different components will never know what is changing in their component and when. Besides, they might be unaware of whether a component is stateless or stateful.   This is why the state is usually said to be encapsulated or having a local scope.This is why the state is usually said to be encapsulated or having a local scope. And therefore, you initialize the state in the class component by simply using a constructor.    Inside the Constructor  To declare a local state in the component, we can use a constructor as follows:   class Welcome extends React.Component {     constructor() {         super();         this.state = {             name: 'Michael Jackson',             currentTimer: 0,             hasPicked: false,             themeRed: false,             todoList: []         }     }     render() {         return My name is {this.state.name};     }  }    And the output or the result of the above < p> tag will be rendered as:     Hello, my name is Michael Jackson However, this was the older convention of declaring a state. We can also declare a state without the ‘constructor’ and ‘super’ keywords with the help of Property Initializer which came in 2017.    Wait, what is Property Initializer?     If you have a lot of code, it becomes harder to understand what is what. And if there are any arguments in the constructor, then it becomes an extra overhead to keep track of all of them.      Therefore, the idea behind using an Initializer is to use a cleaner ES6 component, by assigning an arrow function to a property that will act like a normal method. In other words, it can also be termed as class field syntax.         Without the Constructor       Take a look at the representation below:         class Welcome extends React.Component {  state = {       name: 'Michael Jackson'     }  }  render() {    …  }  }  In the following example, we have added a state to the “Welcome” component.         Let’s see how we can consume the data from the object — not outside the component, but within it!           Rendering data from state                 A state is either initialized in the constructor or by using the class fields syntax to directly initialize it in a class component. Now let’s see how we can consume the state from the component in the render.           A point to note here while using state is we use “this.state” to get the value of the name property and it can be accessed in the render() method as follows:             ~~~Wrong Approach~~~  class Welcome extends React.Component {     constructor() {         super();         this.state = {             name: 'Michael Jackson'         }     }     render() {         const { name } = this.state         return < h1 >My name is {name};     }  } or an alternative to the above is:  ~~~Right Approach~~~ class Welcome extends React.Component {  constructor() {     super();     this.state = {       name: 'Michael Jackson'     }  }  render() {    return < h1 >My name is { this.state.name };  }  } The only difference in both is that in the first snippet I used State as:  const { name } = this.state  But we have already initialized the state in the constructor, why should we do it again?  We should not reassign it, and hence we should never update the component state directly.  A state should always be accessed using this.state.propertyName.  Updating the State So far, we have seen how to create state and use state in the component.      Now let’s understand why and how to update state and what happens after updating a state.           A state can’t be changed directly and the only permissible way of updating it is by using setState as follows:             this.state.site = "Welcome"; // wrong implementation    this.setState({ // correct implementation     site: "Welcome"  });    // Or  this.setState((prevState, props) => ({ site: "Welcome" })))  The setState( ) method makes the component re-render; and hence when a state changes the component re-renders and updates the changes.   Each time setState is called, it sends a request to React to update and re-render and give it back a newly updated state.   Let’s understand this with an example:  Let’s suppose we have a component and want to change the name in the component with a method called handleNameChange(). It should look as follows:          handleNameChange(name) {     this.setState({ name })  }   The above method receives an argument and it uses that argument to update the state.              Component Demo to update a state should look as follows:             class App extends React.Component {     constructor() {         super()         this.state = { name: 'Michael Jackson' }     }     handleNameChange(name) {         this.setState({ name })     }     render() {         const { name } = this.state         return (                              < div>                     < input                         type="text"                         value={this.state.name}                         onChange={event => this.handleNameChange(event.target.value)}                     />                                  My name is, {name}                      )     }  }  When is setState asynchronous?React doesn’t have just one job to do, or only one component to observe for. It is possible that different components will be asking for different updates and DOM manipulations at the same time, hence the state updates are merged!      When setState() is called, React merges the object provided into the current state object.            For example, if we have different variables in our state like this:           constructor(props) {     super(props);     this.state = {         likes: [],         names: []     };  }  And both states can be independently updated by using setState() calls as follow:componentDidMount() {     fetchLikes().then(response => {         this.setState({             likes: response.likes         });     });       fetchNames().then(response => {         this.setState({             names: response.names         });     });  }  Here we are calling multiple setState during one update cycle, so this.setState({names}) will leave this.state.likes unmarked but will completely replace this.state.names.  Hence you will not get the recently updated data in {names} and previous changes will be lost.  A quick fix to the above problem is as follows: Instead of giving a new state directly we can provide a function that can automatically provide the current state into a new state. There are two approaches to this:  // Method #1  this.setState({ foo: this.state.counter + 1 }, this.anyCallback);  Or              // Method #2  this.setState((prevState) => { return { counter: prevState.counterfoo + 1 } }, this.anyCallback);  The main difference is that in example #1, the counter gets incremented by 1 based on the state at the time when you have called the setState() method, whereas In the example-2, the counter will be incremented by 1 only depending on the value that the previous state had while the arrow function was called.  So if we have multiple setState() which happen at the same time before the actual state update, it is possible that they may conflict or have outdated state data, but if we go with approach #2 they are guaranteed to have the most recent updated state because they update synchronously! To learn more about setState() and its powers, head over to this official link.Bonus Section:  Changing Title on Click Example Using StateSo far you have understood how to use State in React and what are the basic principles that define when to use State and when to use Prop. Here is a simple Demo for using State in a component and using Props to reuse the component.    Try this code to understand the power of State and reusable components.         let imgLogo = 'https://apod.nasa.gov/apod/image/2009/CrabNebula_Hubble_960.jpg';    class BonusExample extends React.Component {      constructor() {          super();          this.state = {              newTitle: false          };          this.changeTitle = this.changeTitle.bind(this);      }      changeTitle() {          this.setState({              newTitle: !this.state.newTitle          });      }      render() {          let title = this.state.newTitle ? 'Here is my New Title - Google Page' : 'Here is my Old Title - Facebook Page';          let link;          if (this.state.newTitle) {              link = ;          } else {              link = ;          }          return (              < div>                                                          {link}                                                < button style={{ margin: '20px' }} type="button" className="btn btn-primary" onClick={this.changeTitle}>Change Name                                                          < HelperComponent />                        );      }  }    class OldPageLink extends React.Component {      render() {          return (                                http: //www.facebook.com                        );      }  }    class NewPageLink extends React.Component {      render() {          return (                                http: //www.google.com                        );      }  }    class Header extends React.Component {      render() {          return (                                {this.props.children}                        );      }  }    class Main extends React.Component {      render() {          return (                                {this.props.title}                  {this.props.children}                        );      }  }    class Footer extends React.Component {      render() {          return (                                {this.props.children}                        );      }  }    class LogoComponent extends React.Component {      render() {          return (                        );      }  }    class HelperComponent extends React.Component {      render() {          return (              Changing the title from one to Another          );      }  }    ReactDOM.render(, document.getElementById('example'));  Conclusion       I hope you have understood the concept of State and its usage. We have learned the basic difference between State and Props and when each should be used. We have also understood the data flow in a React component and how to consume and update a State object in React.  Now that you have understood all the fundamentals of State, there are some high-level pointers that you should always keep in mind while using a State. State is private to a component State Updates have shallow merging You should never modify a State Directly Updates in a State may Be asynchronous State is only used when you want to change component dataWe hope you have found this article useful. Happy Learning!   
10470
What Is React-js State?

You must have already learned about the basic buil... Read More

What Are React.Js Prop

Understanding data manipulation in React is never an easy job. React has a unidirectional data flow due to which the technique of data manipulation in React is slightly different than in other frameworks.   To understand the concepts like Props or State, I’d recommend you brush up or go through the data flow concepts in React first. In this article, we’re going to focus only on the Props feature and how to use it in React. We already know that components are reusable, and we can use our component multiple times in our application. To understand props, you should have a solid understanding of the components and how data flows inside the components.  If you don’t know much about React components, I recommend you stop here and read about React components first before continuing! Let’s now learn what are “props” and how to use them?What is Props in React?   We all know that React Components allow you to split the application interfaces into reusable, independent segments.  “Props” stands for properties. It is a special keyword in React which is used for passing data from one component to another.   Logically, components are just like JavaScript functions. They accept random inputs (called “props”) and return React elements which tell what should be displayed on the screen.   Props can be used to pass any kind of data such as:  String Array Integer Boolean Objects or, Functions Understanding ReactJS Props   We are all quite familiar with parent and child components. If you aren’t, then before delving deep into ReactJS props, it’s important to revisit concepts on parent and child components.class ParentComponent extends Component {   render() {    return (      < h1 >        I'm the big parent component.                  ); } }And here is the child component:const ChildComponent = () => {   return I'm a small child! };And did you realize that when we called the child component inside the parent component, we end up rendering the same data again and again? The problem we want to solve here is, we want to render the dynamic data and not static data! Let’s understand this with a simple example. Here we have two components:     One is the parent component which is a class component://this is Parent component import React, { Component } from 'react'; import MyComponent from './MyComponent.jsx'; class App extends Component {    render() {        return (                                                        < /div>        );    } } export default App;And we are rendering the child component ( MyComponent ) which is a functional component inside the parent as follows:import React from 'react'; const MyComponent = () => {    return < h1 > Hello Michael } export default MyComponent;The result will be like this:Hello Michael Hello MichaelThis is coming twice, because we have used twice in our parent component. We can re-use this component any ‘n’ number of times as we want. Now, what if a certain scenario demands that we don’t require this static data in the child component, and we want some dynamic data when the component renders? What I meant is that I want to reuse the child component not with the data it has, but with some other data like:Hello Michael Hello ProfessorHere we can make use of Props or properties. We can add props in the component in the same way that we add attributes in our HTML.Let’s add Props in our older component and see the results:  import React, { Component } from 'react';  import MyComponent from './MyComponent.jsx';  class App extends Component {     render() {         return (                                                                     );     }  }  export default App;  In the above file, we have used a name attribute with the desired dynamic value we want after rendering the data. Now, the most important point here is to pass props to the child component.Passing Props >>>>>  import React from 'react';  const MyComponent = (props) => {     return < h1 > {props.name}   }  export default MyComponent;  If you try to console the value of Props, you will see nothing but a plain JavaScript object with key-value pairs. We can access the value as key of “name” using (.) dot notation like this >>> “props.name“,  In the final step, we have used interpolation to use the props and we enclose it in curly brackets because it is a JSX expression.  Now after calling the child component inside the parent component, here comes the desired output which isHello Michael  Hello Professor Now that we’ve successfully rendered the data of the child component from the parent component, let’s dig deeper!Props in the Constructor:In the above example, we have used a functional component.   What if we have a class component and we want to use props in that component?  Normally, a constructor() method is invoked when a class in a component is created without using the newer public class fields syntax. Most of the times when a constructor() is invoked, the super() method is invoked inside of it. Otherwise, the parent’s constructor will not be executed.  See the snippet below for the class component:  class MyComponent extends React.Component {     constructor(props) {         super(props);         console.log(this.props); // props will be logged here.     }     render() {         return < h1 >Hello {this.props.name};    }  }  To access the props we use this.props.  To summarize the above: If we want to use this.props inside the constructor, we need to pass it in super, or else we can use it in render() without using super()  Using Props in React & Passing Data using Props  Props are mainly used for passing data from the parent component to child component. It motivates us to reuse the components and reduce redundancy as well. But as a growing app, you might see a lot of bugs with typechecking.  In React there is a special inbuilt feature that is used to check the basic validations during typechecking using PropTypes.  See the depth and power of propTypes here:  import PropTypes from 'prop-types'  export default class Mycomponent extends React.Component {     render() {         // .... Your code goes here     }  }  Heading.propTypes = {     content: PropTypes.string.isRequired,     message: PropTypes.array.isRequired,     onClick: PropTypes.func.isRequired,     length: PropTypes.number.isRequired,     styles: PropTypes.object.isRequired,     isReady: PropTypes.bool.isRequired  } PropTypes, a built-in-type checker, ensures that the right type of props is passed to a component. We can define components without propTypes as well, but why risk our application with any wrong data type that might lead to a crash?  NOTE: propTypes can only be checked in development mode (for performance reasons) PROPTYPES exports a huge range of validators which can be used to make sure that the data you receive is checked and valid, completely bug free!   To use typechecking on the props for a component, let’s use and assign the special propTypes property as follows:   import PropTypes from 'prop-types';  class MyComponent extends React.Component {     render() {         return (             < h1 >Hello, {this.props.name}         );     }  }    MyComponent.propTypes = {     name: PropTypes.string  };  In this example, we have used “PropTypes.string”. When an invalid value is provided for a prop, for-ex, other than a string, a warning will be thrown in the JavaScript console. To learn more about prop types, head over here.   Default PropsThere could be certain scenarios in which we need some default props so that props are set even if a parent component doesn’t pass the props down. In this case, we can also define default values for the props directly to the constructor by assigning to the special property known as defaultProps provided by React.  class MyComponent extends React.Component {     render() {         return (             < h1 >Here comes the, {this.props.name}         );     }  }    // Specifies the default values for props:  MyComponent.defaultProps = {     name: 'new value'  };    // Renders "Here comes, new value":  ReactDOM.render(     ,     document.getElementById('dummy')  );        Default props work great in the situation when the same default value can be utilized again and again for every instance of the component. Again reduce the LOC (line of code).  Why are Props useful?  Props provide a medium so that components can talk to each other.  In fact, we can reduce thousands of lines of code just by using Props!     Whenever we declare any component it can be either a class component or a functional component. One thing to notice here is, no matter what kind of component is, it should never change its props value.      Hence the components should act like pure functions (which can’t change their own input) to their props.     But, if you really want to change or introduce some dynamic UIs that should change within the component, you should learn about “State”.     State allows React components to change their values over time without any violations. A state is usually called as an encapsulated one or having a local scope of the component.     It is not accessible to any component other than the one that owns it and sets it.     You can learn about the state in this article.     Can we use Props and State Together?   Absolutely  ! Let’s understand with the following example how we can combine both state and props in our component.    import React from 'react';    class App extends React.Component {     constructor(props) {         super(props);         this.state = {             heading: "Heading from props...",             content: "Some Content from props..."   //Line-8         }     }     render() {        //Line-11         return (                                                                     );     }  }  class Header extends React.Component {     render() {         return (                              < h1 >{this.props.headingProp}                      );     }  }  class Content extends React.Component {     render() {         return (                              < h2 >{this.props.contentProp}                      );     }  }  export default App;          An explanation for the above snippet:  Here we have initialized and used the state in our parent component (line number 7-8) and we have used that state by passing it down the component tree using props.   Inside the render() (line number 11), we are setting the props data as headerProp and contentProp used in child components which are component and component.   Now, if you change the state in the parent component, all the child components get updated, because the single source pf data is State here!    What are the differences between props and state?  Let’s  take a look at some high-level differences between state and props. Although they do similar things, they are used differently.   While both are used for data manipulation, one is of private and the other is of dynamic context.      Props are used to pass data from parent to child whereas the state is used for data manipulation inside the component.  We can get the value of props from the parent component, where we get the value of state object from the initial data defined in the constructor() method.  While this.props is set up by React itself, with this.state we are free to add additional fields to the component manually to store something or in a scenario that doesn’t participate in the data flow.   Props are immutable, i.e We can't change props passed to a component whereas we can change the State, i.e React uses the setState() method to update the object of a state (but within the component itself) Conclusion :    Props is a very crucial concept while learning React. In this article, you have learned about the lifeline of React, which is Props, and how we can use props in React. You have got clarity on why a component updates or re-renders when data in the props changes. We also saw that whenever data changes in props, the component will re-render. Last but not the least, let’s just recall the pointers of all of the above: Props are like parameters to a function  Props cannot be changed, they are immutable  A prop is a special keyword in React, that stands for properties  Props can only be passed in a uni-direction i.e (parent to child)  Props can be used to pass dynamic data to a component A component re-renders when data in the props changeHope you find this article useful! Happy Learning!      
9830
What Are React.Js Prop

Understanding data manipulation in React is never ... Read More

Easier Angular JS Routing With Angular UI Router

Takeaways from this article In this post, we will understand how and why Angular JS Routing is better in comparison to traditional frameworks, and how this routing can be achieved seamlessly with the help of Angular UI Router.  We will understand the usage and importance of states, and how they help in navigating easily through the application. We will see a sample with a state definition and its usage, and how it helps in resolving issues and making the page user-friendly.  Introduction  Angular JS is a popular application framework that is used for front-end development. It works great when creating single page applications. It is written in JavaScript and is being maintained by tech-giant Google. It is used to interpret the HTML attributes in a webpage in the form of directives and bind the respective input and output components of the model, that are represented in the form of JavaScript variables. Angular UI Routing helps navigate between views and pages seamlessly without getting messy, and in a user-friendly manner.  Note: It is assumed that the reader is aware of technologies like HTML, CSS, JavaScript and Angular JS. Native Angular Routing doesn’t have the following facilities: No nested views No named views Data can’t be passed around between two views The syntax of the route should be literally remembered to navigate the page The URL string has to be manually changed via the code base when a URL is changed. When a URL changes, all the links associated with that URL have to be changed and updated to point to the new location.  In order to minimize the above disadvantages, Angular UI Router is used.  Introduction to Angular JS Routing Angular JS Routing is an advanced technique that helps in routing, that has a declarative approach in navigating through the pages of a website. In a webpage, when a link that points to a different page is created, the URL has to be explicitly defined. This path has to be literally memorized and if it is changed, then the URL would have to be changed in all places where it was previously referenced. This is when Angular JS Routing comes into play.  Angular UI Router is a module in Angular JS that helps in the process of routing in Angular JS applications. The Router facilitates in the creation as well as usage of such routes in applications. The Router consists of a method called ‘stateProvider’ which helps in the creation of ‘states’, also known as ‘routes’.  The method ‘stateProvider’ takes the name of the state and the configurations of the state as its parameters. It looks like below:$stateProvider.state(stateName, stateConfig)The above function creates a state in the application. The parameter ‘stateName’ is a string value that is used to create a parent or a child state. To create a child state, the parent state is referenced with the help of the dot operator.  The ‘stateConfig’ parameter is an object that can take many properties, such as: template: It is a string in the form of HTML content or a function that returns a HTML string as the output.  templateUrl: It is a string that is a URL path to a specific template file or a function that returns a URL path string as the output.  templateProvider: It is a function that returns the HTML content as a string output.  Note: The ‘stateConfig’ parameter can take only one property at a time per state or per view with respect to the application.  The states in an application help the user in navigating or reconstituting to the situation that occurs within the application’s working. Note: The latest version of UI Router can be downloaded from the GitHub repository. Below are three examples when ‘stateConfig’ has different properties: With ‘template’ as a property: $stateProvider.state(‘stateName’,   {      url: ‘url for the specific state’,     template: ‘html content’,     controller: "name of controller for specific state" });With ‘templateUrl’ as a property:$stateProvider.state('stateName',   {     url: ‘url for the specific state’,     templateProvider: ‘function name’,     controller: "name of controller for specific state" });Introduction to Angular JS Router It is one of the modules in Angular JS that helps in creating routes for applications that use Angular JS.  Applications are encompassed in a shell, and this shell behaves like a placeholder for the dynamic content that would be generated later.  The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well.  It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on.  Routes are an integral part of Single Page Applications that are preferably created using Angular JS.  With the help of Angular UI Router, these routes can be created with ease and can be used with ease in Angular JS.  The ‘state’ facility gives the flexibility to encapsulate the location of the URL state name, special data for view, generate a view, or even locate a view.  Angular UI Router consists of a ‘stateProvider’ method that can be used to create a route or a state in an application.  The ‘stateProvider’ function takes the name of the state and the configurations of the state as its parameter.  In addition to this, Angular UI Router also helps resolve dependencies before initializing the controller.  It provides utility filters, declarative transitions, state change events, and so on.  What is the difference between State and URL Routes? State Route The views and routes of the Angular JS page will not be bound with just the URL of the site. The specific parts of the site can be changed with the help of UI Routing even if the URL has been kept the same. All the states, routing, and viewing capabilities of the page are handled at a single one-stop place- the ‘.config()’. URL Route URL route is a little different. It is usually implemented using ‘ngroute’, and it needs the implementation of methods such as ‘nginclude’. If the number of methods increases, the situation could get complicated and handling of these methods gets difficult.Stepwise routing with detailed explanation The node.js and npm have to be installed prior to working with the below steps.   For this purpose, the http-server node module has to be run and installed which will help in hosting the demo application that we would create.   It can be installed with the help of the below command: npm install http-server –gA hierarchical directory structure needs to be created. A sample has been shown below:Demo_App --app.js --index.html --nav.htmlThe ‘nav.html’ file needs to have the content as mentioned below: The nav bar title The contents of the file  The two different actions that would be created will also be mentioned here (The home page and the log in.) The index.html file will have the required dependencies along with nav.html file.  The nav.html file will be included in the body tag of the index.html page. The dependencies will be included with the help of ‘CDN’ in the head tag. A separate body tag will be used to define the ui-view div. The ui-view is a section where the information about various routes content and how they would be rendered is present.  The ui-view is a directive that is present inside the ui.router module.  The ui-view directive tells the ‘$state’ about the positioning of the template properties (or other property) It would look like below (sample):  An app.js file can be created, which is an application file that contains the route information and the actions that need to be performed with the help of the controller in the application framework. Below is a sample app.js file:var app = angular.module('Demo_App', [ "ui.router" ]);   app.config(function($stateProvider, $locationProvider,                                   $urlRouterProvider)   {       $stateProvider.state('home_page',   {               url : '/home',               template : "Home page",               controller : "hmeCtrl"         })           .state('login_page',   {               url : '/login',               template : "Login page",               controller : "lgnCtrl"         })       $urlRouterProvider.otherwise("/home");   });   app.controller('mainCtrl', function() {});   app.controller('hmeCtrl', function() {});   app.controller('lgnCtrl', function() {});The first line of the sample code declares the name of the application module and injects a ui.router module dependency into it. Next, the route configurations are defined inside the app.config and the dependency injections are set up.  The routes for the required attributes are set up with the help of the ‘stateProvider’ function and mentioning the required parameters.  Once the home page and the login have been set up, a condition is set up where the page would be redirected back to the home page if any of the routes don’t match the url name. This is done with the help of the ‘otherwise’ function.   Empty states are created for the controllers. This is done since it is a sample and no operation is being performed inside these states.  The above sample application can be run in the browser after the http-serve node module has been installed (as mentioned in the first step of this explanation).   Next step is to navigate to the ‘routingDemo’ folder and execute the below mentioned command:http-serverThis command helps in hosting the demonstration application on the default port that is 8080. This can be accessed with the help of the below mentioned link:localhost:8080/When the application is accessed via a browser, it will be a web application with two routes, namely: Home Login Conclusion In this post, we understood the prominence of Angular JS Routing and Router, and how they are different from the traditional approaches. They help bridge a gap between the features that traditional approaches implement, thereby increasing the ability of web pages to work and perform in a better, more user-friendly manner.Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
6558
Easier Angular JS Routing With Angular UI Router

Takeaways from this article In this post, we will... Read More

What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (Model View Whatever) framework backed by Google and is widely popular for creating dynamic apps. It offers a suite of tools that can be used for building the framework most suited to your single page application development. However, it can also be fully utilized to work for other categories of web pages. It works well with other web-based libraries and is fully extensible. All its features can be modified and even can be replaced to suit your unique development workflow and web feature needs.    As AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Dependency Injection in the following section. IntroductionDependency Injection − AngularJS has a built-in dependency injection (DI) subsystem library whose work is to help the development team by making the application easier to develop, test, and understand. We will learn about each part of DI in detail. The topics we will go through in this article are: Dependency injection in AngularJS Value Injecting a Value Factory Injecting Values into a Factory Service Injecting Values into a Service Providers Configuring a Provider Constants Dependencies Between Modules Dependency injection in AngularJs Today’s software is totally designed in accordance with various design patterns. One such pattern is Dependency Injection. The DI design pattern specifies the pattern in which components are provided with their dependencies, instead of hard coding them within the component. AngularJS comes with a built-in dependency injection mechanism that enables you to divide your application into various types of components which can be injected into each other as their respective dependencies. Modularization of your application makes it easier to use, reuse, configure and even test the different components in your application. According to DI the core types of objects and components include the following: Value Factory Service Provider Constant These are the objects and components which can be injected into each other using AngularJS Dependency Injection. ValueFor AngularJS, the “Value” is a simple object. It can be a number, a string or a POJO (Plain old JavaScript object). This object is used to pass values in AngularJS factories, AngularJS services or AngularJS controllers during the run and config phase. The following example shows the steps involved in using a value. Step 1:  Define a module   var myMod = angular.module("myModule", []); Here, myModule is created using the AngularJS function angular.module(). You can add value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a value object and pass data to it.    myMod.value("numberValue", 10);    myMod.value("stringValue", "aaa");    myMod.value("objectValue", { field1 : 123, field2 : "abc"} );  Here, values are defined using the value () function on the module as created in step 1. The first parameter specifies the name of the value, and the second parameter is the value itself passed to other parts of the application. Factories, services and controllers can now reference these values by their value name. Step 3: Injecting a value in Controller function To inject a value into AngularJS controller function, we need to add a parameter with the same value name as that with which the value was defined. Note that the controller function is registered in angular via the angular.module(...).controller(...) function call. The $scope parameter passed to the controller function is the model for the controller. Thus, here myMod is the module registering the controller as myController, and $scope is the model for myController.  var myMod = angular.module("myModule", []);    myMod.value("numberValue", 10);    myMod.controller("myController", function($scope, numberValue) {     console.log(numberValue);    });Example: Using Value in AngularJS: Consider that you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJs CDN for the same provided by Google.          Value in AngularJS             Value Example     The numberValue is: {{nValue}}        var myMod = angular.module('myModule', []);  myMod.value("numberValue", 5);  myMod.controller('myController', function($scope, numberValue)   {  $scope.nValue =numberValue;  });       Output: Factory In AngularJS, a factory is a function that is used to return a value. This function creates the value on demand whenever a service or controller needs any value injected from the factory. AngularJS applications normally use a factory function to calculate and return a value. The following example shows the steps involved in using a Factory. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a factory object and return data from it.    myMod.factory("myFactory", function() {        return "a value";    }); Here, we have used the factory function to create a Factory named myFactory. This Factory is returning “a value” from it. Step 3: Injecting values into factory Create a controller which gets the factory created value injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a factory value into AngularJS controller function, we need to add a parameter with the same value name as that with which the factory was defined.  var myMod = angular.module("myModule", []);    myMod.factory("myFactory", function() {        return "a value";    });  myMod.controller("MyController", function($scope, myFactory) {    console.log(myFactory);    }); Note: It is not the factory function that is injected, but the value produced by the factory function that gets injected. Example: Using Factory in AngularJS:         Factory                Factory Example    The numberFactory is: {{nFactory}}        var myMod = angular.module('myModule', []);  myMod.factory("myFactory", function() {    return "a value";    });        myMod.controller('myController', function($scope, myFactory) {  $scope. nFactory =myFactory;  });       Output: Service Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injecting it into controllers. The following example shows the steps involved in using a Service. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service for defining the MathService for calculating basic math functions like add, subtract, multiply and divide. And then create another service, myService for defining a cube method to return the cube of a given number: myMod.service('MathService', function() {      this.add = function(a, b) { return a + b };      this.subtract = function(a, b) { return a - b };      this.multiply = function(a, b) { return a * b };      this.divide = function(a, b) { return a / b };  });  myMod.service('myService', function(MathService){       this.cube = function(a) {          return MathService.multiply(a,MathService.multiply(a,a));        }    }); The above code snippet uses MathService to call multiply function that takes two parameters and calculates the product.  Step 3: Inject the service "myService" into the controller   Create a controller which gets the Service injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a Service function into AngularJS controller function, we need to add a parameter with the same value name as that with which the Service was defined.  myMod.controller('myController', function($scope, myService) {        $scope.doCube = function() {          $scope.result = myService.cube($scope.number);       }    }); Here we can even make it event based by adding an event in the main HTML content as:   Enter a number:            Cube      Result of Service: {{result}}      Example: Using Service in AngularJS:         Service Example           Service Example        Result of Service: {{result}}          var myMod = angular.module("myModule", []);  myMod.service('myService', function(){  this.sum = function(a,b) {  return a + b;  }      });  myMod.controller('myController', function($scope, myService) {  $scope.result = myService.sum (5, 6);  });       Output: Provider In AngularJS, a provider is used to internally create other values or services or factory during config phase (the phase during which AngularJS bootstraps itself). Provider can be considered to be the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value or service or factory. The following example shows the steps involved in using a Provider. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service using provider which defines a method square to return the square of a number.  We use provider method to create a Provider.   myMod.config(function($provide) {       $provide.provider('myServiceProvider', function() {          this.$get = function() {             var factory = {};               factory.multiply = function(a, b) {                return a * b;              }             return factory;          };       });    });  Step 3: Inject the Provider "myServiceProvider" into the controller   Create a controller which gets the Provider injected (To understand how to create a Controller, go to the Value part of the article and navigate to its Step 3). To inject a Provider function into AngularJS controller function, we need to add a parameter with the same value name as that with which the provider was defined.  myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {        $scope.number = defaultInput;        $scope.result = myServiceProvider.multiply($scope.number, $scope.number);        $scope.square = function() {               $scope.result = myServiceProvider.multiply($scope.number, $scope.number);         }       });   Example: Using Provider in AngularJS:             Provider               Provider Example                        Enter a number:      X 2              Result: {{result}}                                  var myMod  = angular.module("myModule", []);              myMod.config(function($provide) {    $provide.provider('myServiceProvider', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a) {     return a * a;          }  return factory;      };        });      });             myMod.value("defaultInput", 10);             myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {                $scope.number = defaultInput;                $scope.result = myServiceProvider.multiply($scope.number);    $scope.square = function() {    $scope.result = myServiceProvider.multiply($scope.number);     }        });               Output: Constants Config Phase of AngularJS has some restrictions for injected values, as you cannot inject values into the module.config() function. Instead constants are used to pass values at config phase. To define a constant value we use the constant() function of the defined module. Then for the constant parameter we provide a constant value. The following example shows the steps involved in using a Constant in AngularJS. Step 1: Define a module   var myMod = angular.module("myModule", []);  Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a constant using the constant function and pass constant data to it.      myMod.constant("configParam", "constant value");    Example: Using Constant in AngularJS:              Constant            Constant Example      The numberConstant is:  {{nConstant}}            var myMod = angular.module('myModule', []);      myMod.constant("nConst", 5);      myMod.controller('myController', function($scope,nConst) {  $scope.nConstant =nConst;  });        Output: Difference between Constant and Value Values and Constants seem to be applied in the same way; however, Value differs from Constant in that value cannot be injected into configurations, but it can be intercepted by decorators. Also, a Constant can be used during the apps config phase, whereas a Value is only available during the run phase. The main difference between value and constant is that a value specified using Constant is available during the configuration phase while value specified using Value is available during the run phase. Example showing the difference between a Constant and a Value:          Constant                  Constant Example    {{ID}}          var myMod = angular.module('myModule', []);  myMod.value("myValue", "First Assignment");  myMod.value("myValue", "Second  Assignment");  myMod.constant("myConstant", "First Assignment");  myMod.constant("myConstant", "Second Assignment");  myMod.controller("myController", function($scope, myValue, myConstant) {  console.log("myValue: " + myValue);  console.log("myConstant: " + myConstant);  $scope.ID = " myValue: " + myValue + "&nbsp   myConstant: " + myConstant;  });       Output: Constant Example myValue: Second Assignment myConstant: First Assignment  Complete Example: AngularJS Dependency Injection Let's take an example to deploy all the above mentioned directives.                AngularJS Dependency Injection                 AngularJS Application Showing Dependency Injection         Enter a number:         X  2                Result: {{result}}                          var myMod = angular.module("myMod", []);    myMod.config(function($provide) {    $provide.provider('MathService', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a, b) {    return a * b;          }    return factory;      };        });      });    myMod.value("defaultInput", 10);    myMod.factory('MathService', function() {                var factory = {};                factory.multiply = function(a, b) {    return a * b;  }    return factory;  });           myMod.service('CalcService', function(MathService){    this.square = function(a) {    return MathService.multiply(a,a);     }         });    myMod.controller('myController', function($scope, CalcService, defaultInput) {    $scope.number = defaultInput;    $scope.result = CalcService.square($scope.number);    $scope.square = function() {    $scope.result = CalcService.square($scope.number);      }        });               Output: ConclusionIn the above article we learned about the Dependency Injection in AngularJS. Dependency Injection is a software design pattern that specifies how components get hold of their dependencies. In this pattern, components are given their dependencies instead of coding them directly within the component. We learned about core types of objects and components like Value, Factory, Service, Provider, and Constant. We learned how to create and register an injectable service and configure an injector with a service provider. We learned how to work with Injecting services to a controller. In the end we summarized with a complete example how Providers, Services, Factory and Value can be used.  Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
6563
What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (M... Read More

Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. Introduction  Expressions In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. We will learn about each type of Expression in detail. The topics we will go through in this article are: Introduction to Expressions AngularJS Examples AngularJS using Numbers AngularJS using Strings AngularJS using Objects AngularJS using Arrays AngularJS Expression Capabilities and Limitations. Expressions in AngularJS Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: Can be written inside double braces: {{ expression }}. Can also be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and return the result exactly where the expression is written. Much like JavaScript expressions, they can contain literals, operators, and variables. Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} * Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. AngularJS Expressions and JavaScript expressions Let us compare Expressions in AngularJS and JavaScript. Similarity between AngularJS Expressions and JavaScript expressions: AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. Differences between AngularJS Expressions and JavaScript expressions: Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. It is possible to access the context object using the identifier this and the locals object using the identifier $locals. AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. Filters: You can use filters within expressions to format data before displaying it. No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. No Bitwise, Comma, And Void Operators: You cannot use Bitwise, or void operators in an AngularJS expression. Citation: https://docs.angularjs.org/guide/expression (Docs from AngularJS) Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. AngularJS expressions support filters, while JavaScript expressions do not. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. AngularJS expression cannot declare functions. AngularJS expression cannot contain comma or void. AngularJS expression cannot contain return keyword. There are several categories in which Expressions operate. Some of the Expression Types are: Expressions Using numbers. Example: Expense on Books : {{cost * quantity}} Rs Expressions Using strings. Example: Hello {{student.firstname + " " + student.lastname}}! Expressions Using object. Example: Roll No: {{student.rollno}} Expressions Using array. Example: Marks(Math): {{marks[3]}} Let us go through each category in detail. Expression using Numbers Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   Say if we use the expression as:               My first expression: {{ 5 + 5 }} Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in:              My first expression: 10 We will understand more about the use of number expression in AngularJS with examples. Example: Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js Example Using Curly Braces {{ }} for expressions:       Number Expression of AngularJs      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = 10;  $scope.expr2 = 20  });            Number Expression  The Result of Addition is : {{expr1 + expr2}}         Now run the number expressions as an HTML file and check the output, which will look like this:Example Using ng-init and ng-bind for number expressions:       Number Expression of AngularJs                  The Result of Addition is :                Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Expression using String Expression using String in AngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   * Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  For example: var obj1 = 123;   var obj2 = "A String value";   $scope.isString1 = angular.isString(obj1);   $scope.isString2 = angular.isString(obj2);  isString1 returns false while isString2 returns true. We will see how to use string expressions in detail in AngularJS with the following example: Example:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = "Hello ";  $scope.expr2 = "World";  $scope.expr3 = 100;  var nexpr = $scope.expr3;  var sexpr = $scope.expr1;  $scope.isString1 = angular.isString(sexpr);  $scope.isString2 = angular.isString(nexpr);  });            String Expression    The Result of Concatenation of {{expr1}} and {{expr2}} is :   {{expr1 + expr2}}      The Result of angular.isString() for parameter   {{expr1}} is : {{isString1}}      The Result of angular.isString() for parameter   {{expr3}} is : {{isString2}}           Now run the String expressions as an HTML file and check the output, which will look like this: Expression using Object The object expressions in AngularJS hold object properties in them. AngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  Objects in AngularJS Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. For Example: Considering an object as AngularTraining with fields as Trainer, noOfStd, noOfHours, it can be defined as: $scope.AngularTraining = {  Trainer: ‘Monica’,  noOfStd: 10,  noOfHours: 24  };  To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. Note that $scope in AngularJS is a built-in object which basically binds the “controller” and the “view”. One can define member variables in the $scope within the controller which can later be accessed by the view. We will see how to use object expressions in detail in AngularJS with the following example: Example:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this:Objects with ng-init definition: We can define the objects at ng-init as shown in the following example:       String Expressions of AngularJS                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this: Expression using Array Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. Arrays in AngularJS An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. For example: marks = [95, 52, 65, 98, 55, 35]; We will see how to use array expressions in AngularJS with the following example: Example:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.name = "Monica";  $scope.leave = [1, 2, 0];  });                Array Expression      The Leave Report for the first quarter for Employee:   {{name}} is:    January: {{ leave[0] }}     February: {{ leave[1] }}      March: {{ leave[2] }}      Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}            Now run the Array expressions as an HTML file and check the output, which will look like this:Defining Arrays with ng-init definition: We can define the arrays at ng-init as shown in the following example:       String Expressions of AngularJS                Array Expression      The Leave Report for the first quarter for Employee:   {{name}} is:    January: {{ leave[0] }}     February: {{ leave[1] }}      March: {{ leave[2] }}      Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}            Now run the Array expressions as an HTML file and check the output, which will look like this: Complete Example Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS A complete example of AngularJS expression is:              AngularJS Expressions                  Expression    Hello {{student.firstname + " " + student.lastname}}!  Expense on Books : {{cost * quantity}} Rs  Roll No: {{student.rollno}}  Marks(Math): {{marks[3]}}          Now run the Expressions as an HTML file and check the output, which will look like this: AngularJS Expression capabilities and Limitations AngularJS Expression capabilities Angular expressions have the same power and flexibility as JavaScript expressions.  In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. In AngularJS expressions you can use filters within expressions to format data before displaying it. Angular JS Expression limitations Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression You cannot declare functions in an AngularJS expression, not even inside ng-init directive. You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. Conclusion (Summary) AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as {{ textBinding }}. Some valid expressions are: 1+2, a+b, user.name, items[index] . Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
9159
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-ba... Read More