这有效:
function DetailsCtrl($scope, Plan){
$scope.entities = Plan.query();
}
这不会:
function DetailsCtrl($scope){
var injector = angular.injector(['myApp.services']);
var name = 'Plan';
var Entity = injector.get(name);
$scope.entities = Entity.query();
}
在第二种情况下,不会引发错误,并且 console.log($scope.entities) 会转储加载的实体。但是变量没有在模板中呈现。我猜在用变量填充 $scope 之前正在加载模板。如果是这样,我如何确保 $scope 及时加载了变量?
最佳答案
我创建了一个服务来动态加载资源:
服务:
var m = angular.module('myApp.services', ['ngResource']).
factory('Entity',function($resource){
return {
Plan: $resource('/api/plans/:id',{id: '@id'})
}
}).
value('version', '0.1');
Controller :
function DetailsCtrl($scope, Entity){
$scope.entities = Entity['Plan'].query();
}
关于angularjs - 将资源动态注入(inject) Controller - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12345561/