0

I'm making an ajax call to get some info from a server and then update a list on the screen. The information is coming back, but the scope isn't being updated! I've tried using $apply(), and I'm only getting an error

Code looks like this:

Inside correct controller, in HTML:

<div ng-controller=controller_1>
  <div ng-controller=controller_2>

    <button ng-click="myfunction()">click</button>

  </div>
</div>

In angular controller_1, we have $scope.vendorsarray defined

In the angular controller_2, $scope is injected, we have

$scope.function = function(){

  Factory.ajaxfactoryAction($scope.itemsarray).success(function(data, status, headers, config) {
    $scope.vendorsarray = data

    // POINT A
  }

// POINT B

}

Now, if I do a console.log($scope.vendorsarray) at points A and B, at B (which fires first, because it doesn't have to wait for the ajax), I get the old vendorsarray. At A, I then get the new, correct, vendorsarray. But then vendorsarray still isn't updated in the browser! What's going on?

Thanks for any help.

Edit

Here's how I tried to implement $apply():

$scope.function = function(){

  Factory.ajaxfactoryAction($scope.itemsarray).success(function(data, status, headers, config) {
    $scope.vendorsarray = data

    var temp = $scope.vendorsarray

    $scope.$apply(function() {
      $scope.vendorsarray = temp;
    });
  }

}

Here's the error (in the console):

https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest

Error: error:inprog
Action Already In Progress
$digest already in progress
Will Taylor
  • 1,994
  • 2
  • 23
  • 36

1 Answers1

2

But then vendorsarray still isn't updated in the browser! What's going on?

The problem here (in few words) is that each controller have their own copy of $scope.vendorsarray.

You could use a service to share the data model between both controllers. Angular services are Singletons. Each component dependent on a service gets a reference to the single instance generated by the service factory.

The following example shows the basic structure of this solution:

var app = angular.module('module', [])

.factory('shared', function() {
    var shared = {
      "data": [],
      "counter": 0
    };
    return shared;
  })

.controller('Ctrl1', ['$scope', 'shared',
  function($scope, shared) {
    $scope.shared = shared;
    $scope.add = function() {
      $scope.shared.data.push("Item " + $scope.shared.counter++);
    }
  }
])

.controller('Ctrl2', ['$scope', 'shared',
  function($scope, shared) {
    $scope.shared = shared;
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module">
  <div ng-controller="Ctrl1">
    CONTROLLER 1
    <button ng-click="add()">ADD</button>
  </div>
  <div ng-controller="Ctrl2">
    CONTROLLER 2
    <ul>
      <li ng-repeat="item in shared.data">{{item}}</li>
    </ul>
  </div>
</div>

Related:

Community
  • 1
  • 1
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95