实体返回数据时的回调

时间:2016-12-01 04:10:31

标签: angularjs asynccallback

如何在Device返回数据并将this传递给回调方法时调用回调。

控制器

(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)
           });
       }
   }
})();

服务

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

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

1 个答案:

答案 0 :(得分:1)

如上所述,您可以直接在vm函数中使用updateMap,如下所示。

(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)
           });
       }
   }
})();