Using Forms and Models in AngularJS

In this post I am going to explain, how we can use forms and models in AngularJS. This is my 6th blog in AngularJS series.

Let’s say we want to use a form for my last post where we had a table which showed the rank and name of the site. You can find that link of that demo on plunker here and the link of previous post here. Now what we want to do is take this demo example further bit more and add a form to it for submitting a new site and add a live preview to it using models and also add some validations to it. So, how do we go for it. Let’s start with the full HTML markup here and I would explain about the main parts in below sections.

So, here is the full HTML markup:-

<body ng-controller="myController as controller" style="padding:30px 20px">

  <!--  Top display section -->
  <table class="table table-hover">
    <tr>
      <th>Rank</th> 
      <th>Site</th>
    </tr>
    <tr ng-repeat="siteObj in controller.sites">
      <td>{{siteObj.rank}}</td>
      <td>{{siteObj.site}}</td>
    </tr>
  </table>

  <!--  Site Form -->
  <form name="siteForm" ng-controller="siteController as siteCtrl" ng-submit="siteForm.$valid && siteCtrl.addSite(controller.sites)" novalidate>

    <!--  Live Preview -->
    <table class="table">
      <tr>
        <td>{{siteCtrl.newSiteObj.rank}}</td>
        <td>{{siteCtrl.newSiteObj.site}}</td>
      </tr>
    </table>

    <!--  Submit Form section -->
    <h4>Submit a Site</h4>
    <fieldset class="form-group">
      <select ng-model="siteCtrl.newSiteObj.rank" class="form-control" ng-options="rank for rank in [4,5,6,7,8]" required>
        <option value="">Select Site Rank</option>
      </select>
    </fieldset>
    <fieldset class="form-group">
      <input type="text" ng-model="siteCtrl.newSiteObj.site" class="form-control" placeholder="Please enter a site name..." required />
    </fieldset>
    <fieldset class="form-group">
      <input type="submit" class="btn btn-success" value="Submit Site" />
    </fieldset>

  </form>
</body>

Also here is our js code which contains our modules & controllers part:-

(function() {

  // Sample site array of objects
  var sites = [{
    site: 'Google',
    rank: 1
  }, {
    site: 'Facebook',
    rank: 2
  }, {
    site: 'YouTube',
    rank: 3
  }];

  // Our main module & controller for displaying sites
  var app = angular.module('myModule', []);
  app.controller('myController', function() {
    this.sites = sites;
  });

  // Our 2nd controller for adding new sites to above sites array
  app.controller('siteController', function() {
    this.newSiteObj = {};

    this.addSite = function(sites) {
      sites.push(this.newSiteObj);
      this.newSiteObj = {};
    };
  });

})();

Explanation:-

So, in our HTML top display section we are displaying all the objects in our sites array (that we have declared in js code) by using the  ng-repeat  directive like:-

<tr ng-repeat="siteObj in controller.sites">

I have already explained about  ng-repeat  directive in details in my previous post. If you are more interested about it you can check it out also. 🙂

Next, in the Site Form section we have markup like

<form name="siteForm" ng-controller="siteController as siteCtrl" ng-submit="siteForm.$valid && siteCtrl.addSite(controller.sites)" novalidate>

Here we are doing bunch of things like firstly we have declared the siteController using the  ng-controller  directive and added siteCtrl as alias to it. Next we have used the  ng-submit  directive which tells the browser what action to perform once the form is submitted or a submit button inside the form is clicked. So, once any of the action are performed we first check if the form is valid or not using  siteForm.$valid  where ‘siteForm’ is the name of the form we have given. You can more such error checking options here.

Once the form is valid then only we are calling the  addSite  function which we have defined in our siteController (as you can also see in the js code above). In the  addSite  function we are passing our sites array objects. So, once a new site is submitted it would be added to the current sites array and then would be displayed on our top section table using js code like:-

this.addSite = function(sites) {
   sites.push(this.newSiteObj);
   this.newSiteObj = {};  // This is just used here to clear the live preview once submitted
};

Next, we have a Live Preview section which is implemented using the  ng-model  directive like:-

<input type="text" ng-model="siteCtrl.newSiteObj.site" class="form-control" required />

The ng-model directive basically binds an input, select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. So, whatever data we enter in these controls is added to this new newSiteObj that we have declared in our siteController like this:-

app.controller('siteController', function() {
    this.newSiteObj = {};
});

Next, in the Submit Form section we simply add the required data, see the previews if correct and after we are satisfied with the record we just submit it and then we could see the data we have entered here. But only when we add some data we could submit this form since we have implemented validation in both the controls by adding required attributes to them. 🙂

Demo:
Working Demo on Plunker

That’s it! If you have any comments or suggestion about this post, I would really appreciate it.
Happy Coding 🙂

Advertisements

2 thoughts on “Using Forms and Models in AngularJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s