AngularJS将变量传递给服务

前端之家收集整理的这篇文章主要介绍了AngularJS将变量传递给服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个工厂:

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>

知道我该怎么做?

解决方法

你可以返回一个函数

.factory('getJson',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.

猜你在找的Angularjs相关文章