如何在Ionic中的控制器/视图之间传递数据?

时间:2015-07-03 01:46:10

标签: angularjs ionic-framework ionic

我使用Ionic和Angular创建移动应用程序,需要在两个控制器/视图之间传递数据。

.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');
    };
})

所以,当我执行$ state.go(' tabs.search-results')时,我想确保从搜索返回的数据可以在新视图中加载。这可能非常明显,但我很难找到解决方案。

1 个答案:

答案 0 :(得分:7)

您可以将go方法中的数据作为第二个参数传递,所以

.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");
            });
    };
})    

然后在搜索结果控制器中,您可以访问$ stateParams服务中的数据。

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

    $scope.results = $stateParams.result;

});
相关问题