0

http://host/api当我使用以下参数询问 api 时,我可以访问 JSON api,api URL 是

http://host/api&q=count_people&on=house&house_id=123433

api响应是:

{
    people: "6"
}

api 像前面的例子一样工作,现在当我尝试在我的控制器中使用时,我有以下代码

//app.js
var app = app.module('myapp', ['ngResource']);

app.factory('API', function($resource) {
    var API = $resource('host/api');

    return {
      get: function(o, q, params) {
        s = API.get({on: o, q: q, house_id: params.id}, function(u) {
          return u;
        })
        return s;
      }
    };
});

app.controller('myController', function($scope, API) {
  $scope.ns = {
    count_people: function() {
      return API.get('house', 'count_people', {id: 123433});
    }
  };
});

在我的模板中,我有

<!-- mytemplate.html -->
<p>Total of people in house: {{ns.count_people().people}}</p>

ns.count_people().people 从来没有被称为

4

1 回答 1

1

做你想做的最简单的方法需要分两个步骤。获取数据,显示数据。

http://jsfiddle.net/TheSharpieOne/He9cc/3/ (注意:API 端点不返回任何内容,但您可以看到它被调用。一次。)

var app = angular.module('app', ['ngResource']);

app.factory('API', function ($resource) {
    return $resource('/host/api/');
});

app.controller('myController', function ($scope, API) {
    $scope.ns = {
        count_people: function (id) {
            API.get({on:"house",q:"count_people",house_id:id}, function(data){
                $scope.ns.people[id] = data.people
            });
        },
        people: []
    };
});

HTML 有一组额外的 init 来从 API 中获取计数

<p ng-init='ns.count_people(212321)'>Total of people in house: {{ns.people[212321]}}</p>
于 2013-09-05T20:13:42.850 回答