I am encountering an issue with my Angular application where the data retrieved from a JSON file is not updating in the view when the JSON file is updated. It seems like the JSON file and the view are out of sync.
As a newcomer to Angular, I am struggling to understand why this is happening and how to resolve it. Below is the script I am currently using:
var todoApp = angular.module("todoApp", []);
var model = {
user: "Adam"
};
todoApp.run(function($http) {
$http.get("todo.json").then(function(response) {
model.items = response.data;
});
});
todoApp.filter("checkedItems", function(){
return function(items, showComplete){
var resultArr = [];
angular.forEach(items, function(item){
if(item.done==false || showComplete==true){
resultArr.push(item);
}
});
return resultArr;
}
});
todoApp.controller("Todoctrl", function($scope){
$scope.todo = model;
$scope.incompleteCount = function(){
var count=0;
angular.forEach($scope.todo.items, function(item){
if(!item.done) {count++}
});
return count;
}
$scope.warningClass = function(){
return ($scope.incompleteCount()<3 ? "label-success" : "label-warning");
}
$scope.newTodo = function(actionText){
$scope.todo.items.push({action:actionText, done:false });
}
});
Content of todo.json file:
[
{ "action": "Buy Flowers", "done": false },
{ "action": "Get Shoes", "done": false },
{ "action": "Collect Tickets", "done": true },
{ "action": "Study Geology", "done": false }
]
HTML code snippet:
<body ng-controller="Todoctrl">
<div class="page-header">
<h1>{{ todo.user }}'s To Do List
<span class="label label-default" ng-class="warningClass()"
ng-hide="incompleteCount() == 0">
{{incompleteCount()}}
</span>
</h1>
</div>
<div class="panel">
<div class="input-group">
<input class="form-control" ng-model="actionText">
<span class="input-group-btn">
<button class="btn btn-default" ng-click="newTodo(actionText)">Add</button>
</span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todo.items | checkedItems:showComplete | orderBy: 'action'">
<td>{{item.action}}</td>
<td><input type="checkbox" ng-model="item.done"></td>
</tr>
</tbody>
</table>
<div class="checkbox-inline">
<label><input type="checkbox" ng-model="showComplete"> Show Complete</label>
</div>
</div>