I have a simple template with an input and an anchor link which, upon pressing it, will load another template. I want this second template to fetch the information via a http request.
I am using ng-route to redirect to the search template by default and to the results template from the path /search/:title, and I am trying to use resolve to make the request before loading the results template (code in plunker)
The main problem I am facing is that when I add the resolve the controller stops being initialized (I guess it will load after the promise is returned). This means variables such as the search URL are not initialized and the $routeParams are empty when I print them on the controller search function.
How should I do this?
I am also not sure about the correct syntax for the resolve. Is the first search a scope variable?
resolve: {
search: searchController.search
}
For the ones lazy to check on Plunker, here it is the relevant code:
Routing
.config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/search', {
templateUrl: 'templates/search.html'
}).
when('/search/:title', {
templateUrl: 'templates/result.html',
controller: 'searchController',
resolve: {
search: searchController.search
}
}).
otherwise({
redirectTo: '/search'
});
}]);
searchController
var searchController = search.controller('searchController', ["$http", "$scope", "$location", '$rootScope', '$routeParams', function($http, $scope, $location, $rootScope, $routeParams) {
console.log("Controller constructor");
this.searchURL = 'http://www.myapifilms.com/imdb?title=%thetitle%&format=JSON';
$scope.response = '<Response here>';
this.title = '';
this.defer = null;
console.log("PARAMS: " + JSON.stringify($routeParams));
}]);
searchController.search = function searchMovie($q, $routeParams) {
searchController.defer = $q.defer;
var searchString = $routeParams.title;
url = searchController.searchURL.replace('%thetitle%', searchString);
console.log("URL: " + url);
searchController.searchRequest(url);
};
searchController.searchRequest = function(url) {
$http.get(url).success(function(data) {
....
searchController.defer.resolve();
return searchController.defer.promise;
})
.error(function(data, status, headers, config) {
...
searchController.defer.resolve();
return searchController.defer.promise;
})
};
I think you should create a service with .factory and edit accordingly:
Your plunker forked: http://plnkr.co/edit/Ry4LAl?p=preview
I hope you got what you wanted, share back your plunker after you are done for helping others.