faridghar faridghar - 4 months ago 35x
AngularJS Question

AngularJS $scope.$apply() Dilemma

I'm using AngularJS with Firebase Realtime Database to create a simple list app that syncs across devices. The web client code can be found below.

The problem is that I need to use the $scope.$apply function in my Firebase

callback because this callback is executed from outside of AngularJS and without it, the bindings aren't updated. However, when the user enters a new list item and clicks the Add button, I'm seeing a
angular.js:12520 Error: [$rootScope:inprog]
. I assume that this happens because I'm calling the
method when I'm already inside a

So how can I achieve what I'm trying to do? i.e. use the explicit
method when the callback is triggered outside of AngularJS and do not use it otherwise.

<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var config = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
storageBucket: "XXX",
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var database = firebase.database();
database.ref().on('value', function(snapshot) {
$scope.$apply(function() {
$scope.items = [];
var result = snapshot.val();
for(var key in result) {
var listItem = result[key];
$scope.addItem = function () {
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="x in items">{{x}}</li>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>


FIX 1 -


  ... write your code here 

It will be triggered when the digest cycle is completed.

FIX 2 -

$scope.$$phase will return true if the digest cycle is running else false, but it will not be useful in your case as it doesn't provide any callback function.

Also its not recommended to use