Friday, 10 March 2017

How to use JSON object as model using Controllers ?


You can define your module + controller in <SCRIPT> tag of your HTML file
or
Create a separate JS file and include in your HTML file.

DEFINE MODULE
var app = angular.module('module1', []);

DEFINE CONTROLLER
app.controller("myController", function ($scope) {
   var employee = {
       firstName : "Shaan",
       lastName : "Khan",
       gender : "Male"
   }

   $scope.employee = employee;
});

USE MODEL DEFINED IN CONTROLLER
<div ng-controller="myController"> 
      <div> {{ employee.firstName }} </div>
      <div> {{ employee.lastName }} </div>
 

      <div> {{ employee.gender }} </div>
</div>


If you misspell the controller name :
  • The Angular expressions inside its scope will not be recognized.
  • You can see error in Developer tools (using F12)
To get more detailed and meaningful errors, include angular.js instead of angularjs.min.js in your HTML.

If you misspell property name in expression :

  • No error, It will return null or undefined

No comments:

Post a Comment

Note: only a member of this blog may post a comment.