【问题标题】:Angularjs - Restangular call inside factory/serviceAngularjs - 工厂/服务内的 Restangular 调用
【发布时间】:2014-04-25 02:50:17
【问题描述】:

我使用factory如下:

var appModule = angular.module('appModule', ['ngRoute','restangular']);

appModule
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/home', {
        templateUrl: 'home.html',
        controller:  'ngHomeControl'
      })
      .when('/contacts', {
        templateUrl: 'contacts.html',
        controller:  'ngContactControl'
      });
  }]);

appModule
  .factory('testFactory', function testFactory(Restangular) {
    return {
      getFriendList: function() {
        return Restangular
          .all('api/users/getfriendsinvitations/')
          .getList()
          .then(function(response) {
            //
          });
      } 
    }
  });

appModule
  .controller('ngHomeControl', function($scope, testFactory) {
    $scope.homeFriends = testFactory.getFriendList();
  });

appModule
  .controller('ngContactControl', function($scope, testFactory) {
    $scope.contactFriends = testFactory.getFriendList();
  });

在这里,我无法从 Restangular 调用中获取 $scope.homeFriends$scope.contactFriends 的值。谁能建议我如何使用factory/serviceRestangular 调用中获取值?

【问题讨论】:

  • 由于getFriendList方法返回一个promise,你可能需要使用then回调绑定到你的列表。

标签: angularjs scope angularjs-service restangular angularjs-factory


【解决方案1】:

终于找到了:

appModule
  .factory('testFactory', ['Restangular', function(Restangular) {
    return {
      getFriendList: Restangular
        .all('api/users/getfriendsinvitations/')
        .getList();
    }
  }]);

testFactory.getFriendList.then(function(homeFriends) {
  $scope.homeFriends = homeFriends;
}

【讨论】:

    猜你喜欢
    • 2013-04-20
    • 1970-01-01
    • 2015-11-25
    • 2023-03-08
    • 2023-04-06
    • 1970-01-01
    • 2014-05-02
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多