无法在控制器之间传递数据?

时间:2015-12-29 09:07:14

标签: javascript angularjs controller

我不知道我做错了什么,我试图通过服务全局存储数据并将数据从一个控制器传递到另一个控制器。我将数据存储在一个控制器中,并确认它存储在buildReportController的开头。然后,当我点击我的用户界面上的按钮时,它会打开reportResultsController。但问题是,我可以通过buildReportControllerlocationHistoryService.store()中正确存储数据,但是当我转到reportResultsController and call locationHistoryService.get(), the previousLocation variable in locationHistoryService时`是空的,好像数据从未设置过一样。关于我为什么或如何“全局”存储数据并在控制器之间传递数据的任何想法?以下是我的尝试。谢谢!

在reportView.js

angular.module('reportView', [])
    .service('locationHistoryService', function(){
        var previousLocation = "";
        return {
            store: function(location){
                previousLocation = location;
            },

            get: function(){
                return previousLocation;
            }
        };
});

在buildReport.js

angular.module('buildReport', ['reportView'])
    .controller('buildReportController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
        $rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
            locationHistoryService.store(oldLocation);
            console.log("Old location: ", oldLocation);
        });
}

在reportResults.js

angular.module('reportResults', ['reportView'])
    .controller('reportResultsController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
    console.log("location : ", locationHistoryService.get());
}

2 个答案:

答案 0 :(得分:0)

reportReesults.js中的locationHistoryService.get()方法在buildReport.js中设置之前被调用。

如果你在设置previousLocation变量时宣布它会更好。

在reportView.js

angular.module('reportView', [])
    .service('locationHistoryService',['$rootScope'] ,function($rootScope){
        var previousLocation = "";
        return {
            store: function(location){
                previousLocation = location;
                $rootScope.$broadcast('previous-location-set');
            },

            get: function(){
                return previousLocation;
            }
        };
});

在reportResults.js

angular.module('reportResults', ['reportView'])
    .controller('reportResultsController', ['$rootScope', 'locationHistoryService'], function($rootScope, locationHistoryService){
    $rootScope.$on('previous-location-set', function(){
      console.log("location : ", locationHistoryService.get());          
    });
}

答案 1 :(得分:0)

您的webapp应该只有一个模块,它由angular自动引导,其他模块作为依赖项。编写服务的语法不正确。您编写了.service但返回.factory应返回的对象。以下是代码http://codepen.io/Chyngyz/pen/NxbdpW?editors=101

的工作示例

另外你写的控制器的安全缩小语法不正确,控制器的功能块应该是数组中的最后一项。

相关问题