Click here to Skip to main content
15,884,472 members
Articles / AngularJs

AngularJS: Models: Tutorial 5

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Dec 2015CPOL2 min read 9.7K   5   2
AngularJS: Models: Tutorial 5

Article Series

  1. Tutorial 1: Angular JS
  2. Tutorial 2: Controllers
  3. Tutorial 3: Controllers
  4. Tutorial 4: Controllers: Advanced
  5. Tutorial 5: Models
  6. Tutorial 6: Services

Prerequisites: AngularJS: Controllers: Tutorial 4

In this tutorial, we will enhance our store application to use Model concept. We will create a review and then create a form for the user to dynamically write reviews.

What is ng-model and When It Can Be Used?

The ng–model directive binds the value of HTML controls (input, select, textarea) to application data. The ng–model directive can also:

  • provide type validation for application data (number, email, required)
  • provide status for application data (invalid, dirty, touched, error)
  • provide CSS classes for HTML elements

We will create an array of reviews inside our products and then display it in the beginning. Our controller will now look as below:

JavaScript
var Namespace = angular.module('Namespace', []);
 
Namespace.controller('StoreController', function () {
 this.name = "Aditya S",
 this.bookarray = product
})
 
var product = [ {
 bookName: "Book of Eli",
 bookCost: 15,
 bookImage: 'images/BookStack.png',
 bookDescription: "Thirty years after war turned "
 + " the world into a wasteland, a lone warrior named Eli (Denzel Washington) marches "
 + " across the ruined landscape, carrying hope for humanity's redemption.",
 reviews: [
 {
 stars: 3,
 body: "I love this book!",
 author: "adi@swami.com"
 }, ] },
 {
 bookName: "Introduction to Angular",
 bookCost: 21,
 bookImage: 'images/Books.png',
 bookDescription: "This is me learning Angular JS",
 reviews: [
 {
 stars: 3,
 body: "I love to learn Angular JS",
 author: "adi@swami.com"
 }, ] }]
 
Namespace.controller('PanelSwitcher', function () {
 this.tab = 1;
 this.selectTab = function (setTab) {
 this.tab = setTab;
 };
 this.isSelected = function (checkTab) {
 return this.tab === checkTab;
 };})
 
Namespace.controller('ReviewController', function () {
 
 this.review = {};
 this.addReview = function(product) {
 product.reviews.push(this.review); 
 this.review = {}; };
});

As from the above, I have created an array of reviews and then bind it in HTML as below:

HTML
<blockquote ng-repeat="review in arr.reviews">
<b>Stars: {{review.stars}}</b> {{review.body}}
<cite>by: {{review.author}}</cite></blockquote>

Now let us allow users to enter the reviews. For this, we would need to create a form as below in our HTML. It has a dropdown for number of stars, text area for entering comments and email address and then a button to submit the review.

HTML
    <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" 
	ng-submit="reviewForm.$valid && reviewCtrl.addReview(arr)" class="white-pink">
<select name="dropdown" ng-model="reviewCtrl.review.stars" required class="my-input">
<option value="1">1 star</option>
<option value="2">2 stars</option>
<option value="2">3 stars</option>
<option value="2">4 stars</option>
<option value="2">5 stars</option>
</select>
<textarea placeholder="Comments" ng-model="reviewCtrl.review.body" required class="my-input"></textarea>
<label>by:</label>
<input class="my-input" type="email" placeholder="xyz@abc.com" 
	ng-model="reviewCtrl.review.author" required=""/>
<div> reviewForm is {{reviewForm.$valid}}</div>
<input type="submit" value="Submit" />
</form>

Now, we want to initialize the review, we could do ng-init, but creating a controller is always a better option.

JavaScript
Namespace.controller('ReviewController', function () {

  this.review = {};
   this.addReview = function(product) {
            product.reviews.push(this.review);
            this.review = {};  };
})

I have created an empty review, which will gather all the inputs from the form element and then written a method to push this review to our book store review array. After the push, we want to clear the inputs or initialize again, and hence I have cleared the review using “this.review = {};”.

We will now use “ng-model” to bind the form element value to its property and also update the newly created controller in our HTML.

HTML
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl" 
	ng-submit="reviewForm.$valid && 
	reviewCtrl.addReview(arr)" class="white-pink">
<select name="dropdown" 
ng-model="reviewCtrl.review.stars" required class="my-input">
<option value="1">1 star</option>
<option value="2">2 stars</option>
<option value="2">3 stars</option>
<option value="2">4 stars</option>
<option value="2">5 stars</option>
</select>
<textarea placeholder="Comments" 
ng-model="reviewCtrl.review.body" required class="my-input"></textarea>
<label>by:</label>
<input class="my-input" type="email" placeholder="xyz@abc.com" 
	ng-model="reviewCtrl.review.author" required=""/>
<div> reviewForm is {{reviewForm.$valid}}</div>
<input type="submit" value="Submit" />
</form>

From the above, I have now used “ng-controller” to bind our controller data and then “ng-model” to update the user inputs to the properties. Also, I have done some validation using Angular, which has some powerful client side validations for our directives.

The “ng-submit” will check for whether the form is valid and then try to add a review through our controller. “reviewForm.$valid” is used for checking the validity.

I have also written CSS to show the background of the input boxes as red and green for invalid and valid inputs respectively.

CSS
.my-input.ng-invalid {
 border-color: darkred;
}
 .my-input.ng-valid {
 border-color: green;
}

The outputs are as below:

5

6

The entire solution can be found on GIT at: Tutorial 5.

Happy coding!!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Passionate about Microsoft Technologies like WPF, Windows Azure, ASP.NET, Win Phone and also on Cross platform Mobile Apps, Mongo DB's, IOT & WOT. I love learning and working with (or) Creating Design Patterns . Writer | Technology Evangelist | Technology Lover | Microsoft Developer Guidance Advisory Council Member | Cisco Champion | Speaker |

Blog : http://adityaswami89.wordpress.com/

Comments and Discussions

 
GeneralMy vote of 5 Pin
PVX00724-Dec-15 7:46
PVX00724-Dec-15 7:46 
A truly great series of articles Aditya. A million thanks for taking the time to create them and for posting them.
GeneralRe: My vote of 5 Pin
adityaswami8924-Dec-15 14:34
professionaladityaswami8924-Dec-15 14:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.