ionic中将service中异步返回的数据赋值给controller的$scope

1、service中异步获取数据实例

angular.module('starter.services', [])
.factory('Chats', function($http,$q) {//定义Chats的service
  return {
    all: function() {//all方法异步获取数据
      var deferred=$q.defer(); //定义deferred
      var promise=deferred.promise;//定义promise
      $http.get('http://localhost:3000/lists').success(function(data,status,headers,config){
        //执行deferred.resolve方法,将返回的data传入作为参数
        deferred.resolve(data);
      })
      //返回promise
      return promise;
    }
  };
});

2、controller中执行Chats的all方法,并将返回的数据赋值给$scope的items,这里的result就是service的all方法中异步返回的数据

angular.module('starter.controllers', [])
.controller('ChatsCtrl', function($scope, Chats) {
    Chats.all().then(function(result){
      $scope.items = result;
    },function(){
      console.log('goodsService get error');
    });
})
原文地址:https://www.cnblogs.com/niejunchan/p/5738780.html