Search code examples
javascriptangularjsangularjs-serviceangularjs-digest

Update angular scope on events


I am wrapping a web service client into an angular service. This particular client works emmiting events for particular updates like so:

app.service('AngularClient', function () {
  this.info = null
  this.login = function () {
    client.login(loginInfo).then(function (loggedClient) {
      loggedClient.on('newInfo', function (info) {
        this.info = info
      })
    })
  }
})

A controller uses this service and binds it to its $scope:

app.controller('Ctrl', function (AngularClient, $scope) {
   $scope.client = AngularClient
})

However, anytime the 'newInfo' event gets fired angular doesn't automatically trigger a digest cycle, so I can't control when the info gets updated in the UI. What's the angular way of making sure this happens everytime?


Solution

  • If you want to keep receiving updates to the login event, you could do something like this:

    app.service('AngularClient', function () {
      this.info = null
      this.loginCallback = null
      this.login = function () {
        client.login(loginInfo).then(function (loggedClient) {
          loggedClient.on('newInfo', function (info) {
            this.info = info
            if (this.loginCallback) this.loginCallback(info);
          })
        })
      }
    })
    
    app.controller('Ctrl', function (AngularClient, $scope) {
       $scope.client = AngularClient
       AngularClient.loginCallback = function(info, err){ // optional error
         $scope.user.property = info.property;
         $scope.$apply();
       }
    })