Saturday, March 8, 2014

load Json data in AngularJS




 AngularJS is an open-source JavaScript framework, maintained by Google.
 AngularJS directives allow the developer to specify custom and reusable HTML tags.
  AngularJS directives used below:
ng-app
Declares an element as a root element of the application allowing behavior to be modified through custom HTML tags.
<html ng-app="App" >
In JS, we call  module function 
var App = angular.module('App', []);
ng-controller
Specifies a JavaScript controller class that evaluates HTML expressions. In HTML
<body ng-controller="TodoCtrl">
In JS we call
App.controller('TodoCtrl', function($scope, $http) {
ng-repeat
Instantiate an element once per item from a collection. In HTML
  <li ng-repeat="todo in todos">
{{todo.text}} - <em>{{todo.done}}</em>
</li>
Example: load Json data in ANgularJS
index.html
<!doctype html>
<html ng-app="App" >
<head>
<meta charset="utf-8">
<title>Todos $http</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="TodoCtrl">
<ul>
<li ng-repeat="todo in todos">
{{todo.text}} - <em>{{todo.done}}</em>
</li>
</ul>
</body>
</html>
 
app.js
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
todos.json
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
Reference:
 http://en.wikipedia.org/wiki/AngularJS
http://stackoverflow.com/questions/13020821/how-to-load-json-into-my-angular-js-ng-model

No comments:

Post a Comment