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

fix*_*ate 2 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');
    };
})
Run Code Online (Sandbox Code Playgroud)

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

小智 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");
            });
    };
})    
Run Code Online (Sandbox Code Playgroud)

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

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

    $scope.results = $stateParams.result;

});
Run Code Online (Sandbox Code Playgroud)

  • 我是否需要添加/编辑任何路线?结果ctrl中的$ scope.results为空. (4认同)