On my page, I have an ng-repeat='item in items'
to iterate through $scope.items
.
$scope.items
gets its data when $scope.listItems
is called, which uses $http get data from a REST API connected to a database.
Initially call $scope.items
in the controller to initialize $scope.items and populate it with data.
Now when I add, I know that $http is working because the changes are reflected in the database. $scope.items
is also changed according to my console logging. However, the page does not update to reflect the change.
I think I should be using $scope.$apply()
but I'm just getting "Error: $digest already in progress" so I'm not using it properly. I'm new to AngularJS and dont know alot of Javascript in general so bear with my ignorance.
Here's my code.
var app = angular.module('App', []);
app.controller('AppCtrl', function ($scope, $http) {
$scope.listItems = function () {
$http({method: 'GET', url: '/api/items'})
.success(function (data, status, headers, config) {
$scope.items = data;
console.log($scope.items);
})
.error(function (data, status, headers, config) {
$scope.items = data || 'Request failed';
$scope.status = status;
});
}
$scope.addItem = function () {
$scope.itemDetails.node_type = 'record'; // since input hidden doesnt work
$http({method: 'POST', url: '/api/items/add', data: $scope.itemDetails,
headers: {'Content-Type': 'application/json'}})
.success(function (data, status, headers, config) {
$scope.status = status;
$scope.listItems();
//$scope.$apply(); // throws an error
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
$scope.listItems(); // initialize $scope.items
});