angularjs - 似乎无法将数据从一个 Controller 传递到另一个 Controller

标签 angularjs node.js angularjs-service

问题是我似乎无法将信息从 Controller 1 发送到 Controller 2...我有设置/获取数据的服务,但它不起作用。我收到的实际错误是 Controller 1 的 dataService.getData 不是一个函数...当它在其他地方工作时。

服务 1(在其自己的文件中)

app.service('dataService', function() {
    var data, queried;
    return {
        setData: function(queryData) {
            this.data = queryData;
            this.queried = false;
        },
        getData: function() {
            this.queried = true;
            return this.data;
        }
    }; 
});

Controller 1(发送信息)

app.controller('MyCtrl', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
    anotherService.functionName(function(err, data) {
        // do some things here
        actualService.doesntWork(function(err, data) {
            if (!err) {
                var query = {};
                query.someField = data.someField;
                dataService.setData(query);
                $state.go("go.somewhere.else");
            }
        });
    });
}]);

Controller 2(获取信息)

app.controller('MyCtrl2', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
    $scope.buttonPressed = function() {
        console.log(dataService.getData());
    }
}]);

最佳答案

您没有在 MyCtrlMyCtrl2 中注入(inject)服务 dataService,请确保在使用它之前注入(inject)依赖项。

Controller

app.controller('MyCtrl', ['$scope', '$location', '$state','dataService', //<-added dependency here
   function($scope, $location, $state, dataService) {
    anotherService.functionName(function(err, data) {
        // do some things here
        actualService.doesntWork(function(err, data) {
            if (!err) {
                var query = {};
                query.someField = data.someField;
                dataService.setData(query);
                $state.go("go.somewhere.else");
            }
        });
    });
}]);

Controller 2

app.controller('MyCtrl2', ['$scope', '$location', '$state','dataService',//<-added dependency here 
  function($scope, $location, $state, dataService) {
    $scope.buttonPressed = function() {
        console.log(dataService.getData());
    }
}]);

关于angularjs - 似乎无法将数据从一个 Controller 传递到另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804855/

相关文章:

javascript - AngularJS,在服务中使用 promise

AngularJs 异常处理程序进入无限循环

javascript - 如何向按钮 angularjs 内的字符串添加省略号

javascript - 运行 nightwatchjs 测试时出现 TypeError [ERR_UNESCAPED_CHARACTERS]

node.js - Socket.io 广播不工作

javascript - 无法通过 $resource 获取数组

javascript - Angular 的 $rootScope.$digest

javascript - 将所选内容集成到 AngularJS 中

javascript - 通过 POST 接收 JSON 的 API 接收到的类型与发送的类型不同

angularjs - 如何使用 angularjs 指令将样式标签添加到头部