1

文字列変数を使用してAngularサービスを呼び出す方法はありますか

$scope.serviceList=["yearDetails","monthDetails","dayDetails"];

//controller
$scope.getDetails=function(type,index){

    if(type==$scope.serviceList[index]){

    // if i will call like this yearDetails.query(function(data){}); it is working
    //here i am getting "yearDetails"
     $scope.serviceList[index].query(function(data){
            console.log(data);
     });
    }
}

//service
.factory('yearDetails', function($resource){
           return $resource('/getyearDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
.factory('monthDetails', function($resource){
           return $resource('/getmonthDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
.factory('dayDetails', function($resource){
           return $resource('/getdayDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
4

4 に答える 4

6

文字列で angularJS サービスを取得する方法についての質問に直接答えるには。

// inject $injector to your controller
var yourService = $injector.get('YourServiceName');

それでも、@Markが彼の答えで言ったようなことを複雑にしないでください:)

于 2013-08-16T12:56:21.757 に答える
0
$scope.serviceList=["yearDetails","monthDetails","dayDetails"];

//controller
$scope.getDetails=function(type,index){

    if(type==$scope.serviceList[index]){

     //now i can able to call my service through injector in angular
     var $inj = angular.element('html').injector();
     var serv = $inj.get($scope.serviceList[index]);
     serv.query(function(data){
            console.log(data);
     });
    }
}

//service
.factory('yearDetails', function($resource){
           return $resource('/getyearDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
.factory('monthDetails', function($resource){
           return $resource('/getmonthDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
.factory('dayDetails', function($resource){
           return $resource('/getdayDetails', {}, {
               query: { method:'POST', params:{}, isArray:false }
   });
})
于 2013-08-16T12:34:08.227 に答える
0

次のように、javascript eval functionを使用できます。

var yourService = eval('YourServiceName');
于 2016-08-12T17:06:04.127 に答える