【问题标题】:Callback when entity returns data实体返回数据时的回调
【发布时间】:2017-04-15 14:39:43
【问题描述】:

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

【问题讨论】:

  • 你能解释一下this 指的是什么,控制器、虚拟机还是服务?
  • this 引用控制器。我正在尝试从updateMap 调用控制器中定义的其他方法。
  • 您可以直接在updateMap 中使用vm。我没有发现任何问题。可以试试吗?
  • 谢谢。它奏效了。

标签: angularjs asynccallback


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2014-07-05
    相关资源
    最近更新 更多