【问题标题】:AngularJS pass variable to serviceAngularJS 将变量传递给服务
【发布时间】:2014-09-28 06:20:47
【问题描述】:

我有这个工厂:

factory('getJson', ['$resource', function($resource) {
    return $resource('json/greetings.json', {}, {
      query: {method:'GET', isArray:true}
    });
  }]);

文件是硬编码的,'greetings.json',我希望工厂根据我认为的复选框来获取文件:

<li><input type="checkbox" ng-model="includeVeggies" />Veggies</li>
<li><input type="checkbox" ng-model="includeGreetings" />Greetings</li>

知道我该怎么做吗?

【问题讨论】:

    标签: angularjs angularjs-service angularjs-resource


    【解决方案1】:

    你可以返回一个函数:

    .factory('getJson', ['$resource', function($resource) {
        return function (file) {
            return $resource(file, {}, {
                query: {method:'GET', isArray:true}
            });
        };
    }]);
    

    然后在你的控制器中:

    .controller('MyController', ['getJson', function (getJson) {
        getJson('json/greetings.json');
    });
    

    Here's a Plnkr.

    【讨论】:

    • 它返回未定义。
    • 另外,这种方式,如何在服务器获取文件后才进行回调分配响应?
    • 抱歉,有错别字。
    • 知道了!我错过了 getJson('json/greetings.json').query()
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2021-04-01
    • 2016-05-26
    相关资源
    最近更新 更多