2013-10-20 85 views
0

我有这个控制器正在为Angular UI typeahead正确工作。我如何将服务器调用添加为资源?

var receivableApp = angular.module('receivableApp', ['ui.bootstrap', 'ngResource']) 
.controller('ReceivableController', function ($scope,$http) { 
    $scope.Debtors = function (term) {   
     return $http.get('/Receivable/GetDebtors/?term=' + term).then(function (response) {     
      return response.data; 
     }); 
    }; 
}); 

回答

1
receivableApp.factory('GetDebtors', ['$resource', 
    function($resource){ 
     return $resource('/Receivable/GetDebtors/'); 
    }]); 

这将添加一个服务GetDebtors具有默认GET,和其他REST处理程序。

现在,让你的控制器内的电话,你可以这样做:

debtControllers.controller('DebtCtrl', ['$scope', 'GetDebtors', 
    $scope.debts = GetDebtors.get({term: 'foo'}); 
]); 

这相当于拨打电话到/Receivable/GetDebtors/?term=foo

如果要更改行为,可以覆盖$resource上可用的默认方法。更多细节可以在here找到。

0

$资源是为了从端点检索数据,操纵它并将其发送回来。在你的资源上使用自定义方法很好,但是你不想错过OOTB.var Todo = $ resource('/ api/1/todo /:id')的很酷的功能。 ;

//创建待办事项var todo1 = new Todo(); todo1.foo ='bar'; todo1.something = 123; todo1。$ save();

+0

谢谢保罗。我真的想要一个基于我上面的代码的例子。我已经看过所有的Todo例子,但我需要知道如何传递参数等。这就是为什么我标记了上面的答案。 – Greg

+0

可以使用以下参数调用类对象或实例对象上的操作方法:HTTP GET“class”操作:Resource.action([parameters],[success],[error])非GET“class”操作: Resource.action([参数],postData,[成功],[错误])非GET实例操作:实例$ action([参数],[成功],[错误]) –

+0

根据参数进行调用的语法 –