1

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
});
kentwait
  • 1,969
  • 2
  • 21
  • 42
  • 2
    Can you show your HTML as well... you shouldn't call $scope.$apply() from within angular scope/services. $http automatically causes the $apply and $digest to be called which will update any watches that are established by checking for any dirty (changes) in the scope. What you're doing looks generally right have you tried just showing {{items}} somewhere on the page? – shaunhusain Jul 19 '13 at 05:48
  • 1
    Hey you're right it does work! I found out that I was calling `ng-controller="AppCtrl"` in two divs nested with each other. So I guess that was what was throwing it off – kentwait Jul 19 '13 at 06:23

0 Answers0