2

I am using Ionic and Angular to create a mobile application and need to pass data between two controllers/views.

.controller('SearchCtrl', function($scope, $state, $http) {
    $scope.search = function() {
        console.log('Starting search..');
        var res = $http.post('http://endpoint:8080/search',{"language":"en"})
            .success(function(data) {
            //take the data.results and make sure its available when I move to tab.search-results   
            alert("Search OK");
        })
            .error(function(data) {
            alert("Search Bad");
        });

        //take the data.results and make sure its available when I move to tab.search-results
        $state.go('tabs.search-results');
    };
})

So when I do the $state.go('tabs.search-results') I want to make sure the data returned from search is available for loading in the new view. This is probably really obvious but I am struggling to find a solution.

1

1 Answer 1

7

You can pass the data in the go method as the second argument, so

.controller('SearchCtrl', function($scope, $state, $http) {
    $scope.search = function() {
        console.log('Starting search..');
        var res = $http.post('http://endpoint:8080/search',{"language":"en"})
            .success(function(data) {
                alert("Search OK");
                //take the data.results and make sure its available when I move to tab.search-results
                $state.go('tabs.search-results', {result: data});
            }).error(function(data) {
                alert("Search Bad");
            });
    };
})    

Then in the search results controller you can access the data from the $stateParams service.

.controller('SearchResultsCtrl', function($scope, $state, $stateParams) {

    $scope.results = $stateParams.result;

});
3
  • awesome let me give this a try now!
    – fixulate
    Jul 3, 2015 at 2:42
  • 4
    Do I need to add/edit any routes? The $scope.results in the results ctrl is empty..
    – fixulate
    Jul 3, 2015 at 3:25
  • 1
    Yes. You do need to update the route. Modify the url section of the route to: url: '/search-results/:result',
    – Gilad M
    Sep 1, 2016 at 10:43

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.