简体   繁体   中英

AngularJS reference factory.function from external module

I have two distinct application files for angularjs defined below:

search.js

var app = angular.module('search',['ngGrid']);
    app.factory('answers',function($http){  
        return{  
           search: function(params,success,error){  
            //code to execute over rest    
         },  
            otherSearch: function(params,success,error){  
            //code to execute over rest    
         }
        };  
});

results.js

var app = angular.module('results',['ui.bootstrap','ngGrid']);  
    app.controller('resultsCtrl',function($scope,$http,search) // search should reference search.js  
    search.search();  
    search.otherSearch();

});

What I am trying to do is reference the search and otherSearch functions within search.js from results.js however, this is failing with unknown provider when I do this:

var app = angular.module('results',['ui.bootstrap','ngGrid','search']);  

what is the correct way to make it so I can invoke FACTORY methods that are contained within search.js

In the following code, all you are doing is re-declaring your Angular app with the name search :

var app = angular.module('search',['ngGrid']);

It is in this code below that you're actually declaring the factory, and you've named it answers :

    app.factory('answers',function($http){  
        return{  
           search: function(params,success,error){  
            //code to execute over rest    
         },  
            otherSearch: function(params,success,error){  
            //code to execute over rest    
         }
        };  
});

I think the problem is you're trying to inject answers as search . Try this instead:

app.controller('resultsCtrl',function($scope,$http,answers)
    answers.search();  
    answers.otherSearch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM