19

I have a controller which has a function to get some alerts from an API and update a count on the front-end of my site which is bound to the alert.

Unfortunately the ng-bind attribute I'm using doesn't seem to be updating the count live, even though a simple console.log() is telling me that the actual alert count is being updated in the controller.

Front-end

<div class="modeSelector modeSelector_oneUp" data-ng-controller="MyLivestockController as vm">
    <a class="modeSelector-mode" data-ui-sref="my-livestock">
        <div class="modeSelector-type">Alerts</div>

        <img class="modeSelector-icon" src="/inc/img/_icons/envelope-black.svg" onerror="this.src=envelope-black.png" />

        <span data-ng-bind="vm.alertCount"></span>
    </a>
</div>

Controller

(function() {

  'use strict';

  function MyLivestockController(userService) {

    var vm = this;

    vm.myLivestockNotification = {
      isLoading: true,
      hasError: false
    };

    vm.alertsNotification = {
      isLoading: true,
      hasError: false,
      hasData: false
    };

    vm.deleteAlert = function(id) {

      vm.currentAlert = void 0;
      vm.alertsNotification.isLoading = true;

      userService.deleteAlert(vm.user.id, id).then(function() {

        // Remove the alert from our Array
        vm.alerts = vm.alerts.filter(function(alert) {
          return alert.id !== id;
        });

        // Refresh the alert count for the user
        vm.getAlerts(vm.user.id);

        vm.alertsNotification.isLoading = false;
        vm.alertsNotification.hasError = false;
      }, function() {
        vm.alertsNotification.hasError = true;
      });
    };

     vm.getAlerts = function(id) {
        userService.getAlerts(id).then(function(alertData) {
          vm.alertCount = alertData.length;

          if (vm.alertCount > 0) {
            vm.alertsNotification.hasData = true;
          } else {
            vm.alertsNotification.hasData = false;
          }

          vm.alerts = alertData;

          vm.alertsNotification.isLoading = false;
          vm.alertsNotification.hasError = false;
        }, function() {
          vm.alertsNotification.hasError = true;
        });
    };

    // Init
    (function() {
      userService.getCurrentUser().then(function(data) {
        vm.myLivestockNotification.hasError = false;
        vm.myLivestockNotification.isLoading = false;

        vm.user = data;

        // Get alert count for the user
        vm.getAlerts(vm.user.id);
      }, function() {
        vm.myLivestockNotification.hasError = true;
      });
    })();
  }

  angular
    .module('abp')
    .controller('MyLivestockController', MyLivestockController);

})();

Service

(function() {

  'use strict';

  function userService($q, $sessionStorage, $localStorage, $filter, user) {

    var service = this;

    service.getAlerts = function(id) {
      var deferred = $q.defer();

      user.alerts({ userID: id }, function(response) {
        if (response.hasOwnProperty('data')) {

          // Convert dates to valid Date
          angular.forEach(response.data, function(alert) {
            /* jshint camelcase: false */
            if (alert.created_at) {
              alert.created_at = $filter('abpDate')(alert.created_at);
            /* jshint camelcase: true */
            }
          });

          deferred.resolve(response.data);
        }
        else {
          deferred.reject('DATA ERROR');
        }
      }, function(e) {
        deferred.reject(e);
      });

      return deferred.promise;
    };

  angular
    .module('abp')
    .service('userService', userService);

})();

As you can see, I've got my getAlerts() function being called every time an alert is deleted, using the deleteAlert() function, but the <span data-ng-bind="vm.alertCount"></span> on the front-end only updates after refreshing the page, where I'd like it to update live.

5
  • Have you tried ng-model
    – nosdalg
    May 8, 2015 at 8:50
  • 1
    change it to ng-model = "vm.alertCount" that should work May 8, 2015 at 8:53
  • @PaulFitzgerald. ng-model can't be used with span.
    – Zee
    May 8, 2015 at 8:57
  • @Sourabh- ah interesting, I didn't know that. Thanks May 8, 2015 at 8:58
  • 1
    Look at my answer and stop confusing the guy. The value he bound to is updated on a promise from service, and thus outside of digest. $scope.apply() should fix the problem. May 8, 2015 at 8:58

2 Answers 2

32

Your bind is not updating because you change the value of alertCount outside of digest cycle of your angular app. When you refresh your app, the digest runs and thus your value gets updated. Wrap the update of the variable in $scope.apply() like so:

$scope.$apply(function(){
    vm.alertCount = alertData.length;
});

This will force digest and update the value live.
If you have more values that are updated outside of digest (any callback, promise etc) you can force digest cycle by calling:

$scope.$apply();

Hope it helps.

EDIT -----
Given your update with full code, I see that you are not injecting scope anywhere in your controller, the controllers I write usually start like that:

(function () {

var app = angular.module('mainModule');

app.controller('myController', ['$scope', '$myService', function ($scope, $myService) {

    //logic
}]);
}());

EDIT -----
Here is a quick go I had on your code:

(function() {
'use strict';


var app = angular.module('abp');

app.controller('MyLivestockController', ['$scope', 'userService', function($scope, userService) {

    var vm = {};
    $scope.vm = vm;

    vm.myLivestockNotification = {
        isLoading: true,
        hasError: false
    };

    vm.alertsNotification = {
        isLoading: true,
        hasError: false,
        hasData: false
    };

    vm.deleteAlert = function(id) {

        vm.currentAlert = void 0;
        vm.alertsNotification.isLoading = true;

        userService.deleteAlert(vm.user.id, id).then(function() {

            // Remove the alert from our Array
            vm.alerts = vm.alerts.filter(function(alert) {
                return alert.id !== id;
            });

            // Refresh the alert count for the user
            vm.getAlerts(vm.user.id);

            vm.alertsNotification.isLoading = false;
            vm.alertsNotification.hasError = false;
        }, function() {
            vm.alertsNotification.hasError = true;
        });
    };

    vm.getAlerts = function(id) {
        userService.getAlerts(id).then(function(alertData) {
            vm.alertCount = alertData.length;

            if (vm.alertCount > 0) {
                vm.alertsNotification.hasData = true;
            } else {
                vm.alertsNotification.hasData = false;
            }

            vm.alerts = alertData;

            vm.alertsNotification.isLoading = false;
            vm.alertsNotification.hasError = false;

            //important, this is promise so we have to apply the scope to update view
            $scope.$apply();
        }, function() {
            vm.alertsNotification.hasError = true;
        });
    };

    // Init
    (function() {
        userService.getCurrentUser().then(function(data) {
            vm.myLivestockNotification.hasError = false;
            vm.myLivestockNotification.isLoading = false;

            vm.user = data;

            // Get alert count for the user
            vm.getAlerts(vm.user.id);
        }, function() {
            vm.myLivestockNotification.hasError = true;
        });
    })();
}]);

})();

The general idea is:

  1. you create an app (angular.module)
  2. you create a controller in this app, with $scope injected
  3. any values you want to be updated on your view, you add to $scope
  4. if you have any $scope updates in a callback, event or promise, you wrap them in (or follow with) $scope.$apply call

I think this should work for you :)

2
  • Thanks, Daniel. I'm struggling to apply $scope.apply(), however, as I'm getting console errors when doing so. I've updated my original code to offer clarity and the full controller, am I right in thinking my $scope is not defined errors are because I'm referencing scope as vm?
    – Alex Ryans
    May 8, 2015 at 9:04
  • I edited my answer with a code that should work for you. May 8, 2015 at 10:14
2

I have attempted to reproduce your code below with a mock userService, and some slight modifications to the html view so we can more clearly see the alerts and delete them. I have not modified your Controller.

This appears to work, yes?

Which leads me to believe there may be some issue with the implementation of your userService. If you are able to post the relevant code, I can update this answer with a clarified solution.

UPDATE: As you've updated your question with the userService code, I've updated the below to more closely match. I still have a mock service standing in place of the user dependency of the userService. Additionally I made a couple of small edits to the Controller class so that while promises are still resolving we can see 'Updating...' in place of the alerts count.

This all still appears to work, unless I'm misunderstanding - will think on it more and update this 'answer' when I can think of where else to investigate for the source of the issue, see if we can at least reproduce it!

(function() {

  'use strict';

  function MyLivestockController(userService) {

    var vm = this;

    vm.myLivestockNotification = {
      isLoading: true,
      hasError: false
    };

    vm.alertsNotification = {
      isLoading: true,
      hasError: false,
      hasData: false
    };

    vm.deleteAlert = function(id) {

      vm.currentAlert = void 0;
      vm.alertsNotification.isLoading = true;

      return userService.deleteAlert(vm.user.id, id).then(function() {

        // Remove the alert from our Array
        vm.alerts = vm.alerts.filter(function(alert) {
          return alert.id !== id;
        });

        // Refresh the alert count for the user
        vm.getAlerts(vm.user.id).then(function() {
          vm.alertsNotification.isLoading = false; //put here, loading isn't really finished until after .getAlerts() is done
          vm.alertsNotification.hasError = false;
        });

      }, function() {
        vm.alertsNotification.hasError = true;
      });
    };

    vm.getAlerts = function(id) {

      vm.alertsNotification.isLoading = true;

      return userService.getAlerts(id).then(function(alertData) { //return the promise so we can chain .then in .deleteAlert()
        vm.alertCount = alertData.length;

        if (vm.alertCount > 0) {
          vm.alertsNotification.hasData = true;
        } else {
          vm.alertsNotification.hasData = false;
        }

        vm.alerts = alertData;

        vm.alertsNotification.isLoading = false;
        vm.alertsNotification.hasError = false;
      }, function() {
        vm.alertsNotification.hasError = true;
      });
    };

    // Init
    (function() {
      userService.getCurrentUser().then(function(data) {
        vm.myLivestockNotification.hasError = false;
        vm.myLivestockNotification.isLoading = false;

        vm.user = data;

        // Get alert count for the user
        vm.getAlerts(vm.user.id);
      }, function() {
        vm.myLivestockNotification.hasError = true;
      });
    })();
  }

  function userMock($q, $timeout, $log) {
    var _alerts = {
        data: [{
          id: 1,
          message: "He doesn't sleep, he waits..."
        }, {
          id: 2,
          message: "He doesn't mow his lawn, he stands outside and dares it to grow."
        }, {
          id: 3,
          message: "Some magicians can walk on water. He can swim through land."
        }]
      },
      _currentUser = {
        id: 'Q2h1Y2sgTm9ycmlz'
      };

    return {
      getCurrentUser: function getCurrentUser() {
        $log.log("getCurrentUser");
        //return $q.when(_currentUser);
        return $timeout(function() { //use $timeout to simulate some REST API latency...
          return _currentUser;
        }, 500);
      },
      getAlerts: function getAlerts(id) {
        $log.log("getAlerts: " + id); //not doing anything with the id in this mock...
        $log.log(_alerts.data);
        //return $q.when(_alerts);
        return $timeout(function() {
          return _alerts;
        }, 500);
      },
      deleteAlert: function deleteAlert(userId, id) {
        $log.log("deleteAlert: " + userId + " :: " + id);

        //return $q.when(_alerts);
        return $timeout(function() {

          for (var i = 0; i < _alerts.data.length; i++) {
            if (_alerts.data[i].id === id) {
              _alerts.data.splice(i, 1);
              $log.log("alert found and deleted");
              break;
            }
          }

          $log.log(_alerts.data);

          return _alerts;
        }, 500);
      }
    };
  }

  function userService($q, $timeout, $log, userMock) {

    var service = this;

    service.getCurrentUser = userMock.getCurrentUser;

    service.getAlerts = function(id) {
      var deferred = $q.defer();

      userMock.getAlerts(id).then(function(response) {
        if (response.hasOwnProperty('data')) {

          // Convert 'he' to 'Chuck Norris'
          angular.forEach(response.data, function(alert) {
            if (alert.message) {
              alert.message = alert.message.replace(/he/gi, "Chuck Norris");
            }
          });

          deferred.resolve(response.data);
        } else {
          deferred.reject('DATA ERROR');
        }
      }, function(e) {
        deferred.reject(e);
      });

      return deferred.promise;
    };

    service.deleteAlert = function(userId, id) {
      var deferred = $q.defer();

      userMock.deleteAlert(userId, id).then(function(response) {
        deferred.resolve(response.data);
      }, function(e) {
        deferred.reject('DATA ERROR');
      });

      return deferred.promise;
    };

    return service;
  };


  angular
    .module('abp', [])
    .service('userMock', userMock)
    .service('userService', userService)
    .controller('MyLivestockController', MyLivestockController);

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="abp">

  <div data-ng-controller="MyLivestockController as vm">
    <div>Alerts</div>
    <span data-ng-bind="vm.alertsNotification.isLoading ? 'Updating...' : vm.alertCount"></span>
    <div data-ng-repeat="alert in vm.alerts">
      {{alert.id}}: {{alert.message}}
      <button ng-click="vm.deleteAlert(alert.id)">Delete</button>
    </div>
  </div>

</div>

3
  • Hi @JcT, thanks for your reply, I've updated the original post with the user service.
    – Alex Ryans
    May 11, 2015 at 10:05
  • Thanks, @AlexRyans, happy to help - I've done a quick update above as well, but still trying to zero in on it; if I can figure out how to reproduce the problem, will hopefully have better luck in finding the source of it!
    – JcT
    May 11, 2015 at 15:27
  • I think the next step is going to be trying to come up with the simplest set of code that reproduces the issue in a snippet or plunkr; make sense?
    – JcT
    May 11, 2015 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.