AngularJs Model
AngularJS Model
- Model in Angular is a JavaScript Object that stores data.This data can either be user-entered data or application initialized data.
- Application can use Angular Expressions or Angular controllers to declare and initialize data.
- Unlike server-side MVC frameworks, AngularJS will not require user to create model by inheriting from any specific class or write special getter or setter methods to get/set its values.
- Once entered by the user or initialized by the application, the model can be modified and manipulated as per requirement.
- Angular model can be declared using any valid identifier name. For example: username, mobile.
- Angular model can be initialized with the values having valid JavaScript data types. i.e. String, Boolean, Array, Number and Object. For example: username=“John”, mobile=1234
- Angular Model can also be initialized as JavaScript object. For example : user.username, user.mobile where user is the Angular model created and username and mobile are the properties attached to it.
Model Creation |
Syntax |
|
1. User entered data |
ng-model |
<input type="text" name="email" id="email" ng-model="emailid"> |
2. Application initialized data |
ng-init |
<tr ng-init="mobile=1234567890"> |
Angular Expressions |
{{emailid=‘sample@hotmail.com’}} |
|
Let us see now how to initialize model
AngularJS Model Initialization - Demo
- Use of ng-model for model creation
- Use of ng-init for model creation and initialization
- Use of Angular expression for model creation and initialization
Let us design an Angular web page 3-ModelCreation, where we will use Angular Models to store/capture data. The web page should look, as shown below.
Let us now create the page.
CODE/PROGRAM/EXAMPLE
<html ng-app>
<head>
<script src="lib/Angular/angular.js"></script>
</head>
<body>
<p><label for="username">Username:</label>
<input type="text" name="username" ng-model="username" id="username" >
<span id="displayUsername"> Your username is:<i>{{ username}}</i> </span></p>
<p ng-init="mobile = 1234567890"><label for="mobile">Mobile:</label>
<input type="number" name="mobile" ng-model="mobile" id="mobile" >
<span id="displayMobile"> Your mobile number is:<i>{{ mobile}}</i> </span></p>
<p><label for="password">Password:</label>
<input type="password" id="password" ng-model="password" name="password" />
<span id="displayPassword"> Your entered the password: <i>{{password = ‘default password’}}</i> </span></p>
</body>
</html>