Santosh Santosh - 9 days ago 8
AngularJS Question

Callback when entity returns data

How to call callback when

Device
returns data and pass
this
to the callback method.

Controller

(function() {
'use strict';

angular
.module('frontendApp')
.controller('DeviceController', DeviceController);

DeviceController.$inject = ['$scope', '$state', 'Device'];

function DeviceController ($scope, $state, Device) {
var vm = this;

vm.devices = [];

loadAll();

function updateMap(flag){
var self = this;//how to pass "this" from loadAll()?
// logic to update map
}

function loadAll() {
Device.query(function(result) {
vm.devices = result;
// Callback function here - updateMap(true)
});
}
}
})();


Service

function Device ($resource, DateUtils) {
var resourceUrl = 'api/devices/:id';

return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'update': { method:'PUT' }
});
}

Answer

As discussed, you can use vm directly inside the updateMap function as below.

(function() {
   'use strict';

   angular
       .module('frontendApp')
       .controller('DeviceController', DeviceController);

   DeviceController.$inject = ['$scope', '$state', 'Device'];

   function DeviceController ($scope, $state, Device) {
       var vm = this;

       vm.devices = [];

       loadAll();

       function updateMap(flag){
         console.log(vm.devices);
       }

       function loadAll() {
           Device.query(function(result) {
               vm.devices = result;
               // Callback function here - updateMap(true)
           });
       }
   }
})();