我有一项通过宁静的超薄API收集数据的服务。
test.factory('DataService', function ($http, $log, $resource) {
return $resource('php/planets')
});
test.controller('tableviewCtrl', function ($scope, DataService, $resource) {
DataService.query(function(response) {
$scope.matches = response;
});
});
我有一个指令:
<tableview data="{'view': 'planets', 'settings': {'search': 'false'}, 'cols': ['id','name','region'] }"></tableview>
,例如指令:
<tableview data="{'view': 'superheroes', 'settings': {'search': 'false'}, 'cols': ['id','name','strength'] }"></tableview>
根据“view”参数,我想更改服务中的$resource
网址。例如,从php/planets
到php/projects
知道如何处理这件事吗?
修改
test.factory('DataService', function ($http, $log, $resource) {
resourceName = 'planets';
return {
changeResource: function ( resourceName) {
resourceName = resourceName;
},
data: $resource('php/'+resourceName)
}
});
test.controller('tableviewCtrl', function ($scope, DataService, $resource) {
DataService.changeResource('superheroes').then(function () {
DataService.data.query(function(response) {
$scope.matches = response;
});
});
});
有人可以帮忙吗?
答案 0 :(得分:1)
我会为使用ngInit指令初始化的每个<tableview>
使用内部控制器。
使用Javascript:
test.service('DataService', function ($http, $log, $resource) {
return {
resourceName = 'planets';
changeResource: function (resourceName) {
this.resourceName = resourceName;
},
data: $resource('php/' + resourceName)
}
});
test.controller('tableviewCtrl', function ($scope, DataService, $resource) {
// am I still necessary?
});
test.controller('innerCtrl', function ($scope, DataService, $resource) {
$scope.init = function(resourceName) {
DataService.changeResource(resourceName);
DataService.data.query(function(response) {
$scope.matches = response;
});
};
});
HTML:
<tableview
ng-controller="innerCtrl"
ng-init="init('planets')"
data="{'view': 'planets', 'settings': {'search': 'false'}, 'cols': ['id','name','region'] }">
</tableview>