angularjs - 在 Controller AngularJS 之间共享数据

标签 angularjs angularjs-service

我试图将一个充满对象的数组从 Controller 1 发送到 Controller 2。但我在 Controller 2 中得到的只是一个空数组。我得到一个填充的唯一方法是在我的服务中创建一个静态数组。

我的服务

app.service('myData', function () {
this.myData = [];

this.addData = function(data) {
    this.myData.push(data);
}
this.getData = function() {
    return this.myData;
}});

设置数据的 Controller 1
app.controller('controller1',['$scope', 'myData', function($scope, myData) {
    $scope.addData = function(index, name) {
        myData.addData({index: index, name: name});
    }}]);

Controller 2 看起来像这样
app.controller('controller2',['$scope', 'myData', function($scope, myData) {

$scope.myData = myData.getData();
$scope.$watch('myData.getData()', function(data){
    console.log(data);
});
console.log($scope.myData);}]);

当我在寻找答案时,我发现了很多与我几乎相似的问题。唯一的区别是我从我的 Controller 填充我的服务而不是创建一个静态服务。

我的 console.logs 都返回一个空数组。为什么是这样?

最佳答案

您的 $watch表达式应该是一个函数( see the docs for $watch )。捐赠 $watch一个字符串告诉 Angular 检查 $scope 上的属性.除此之外,您还错误地引用了您的 myData服务作为字符串中的“数据”'data.getData()' .

1) 查看myData#getData的结果:

$scope.$watch(function () {
    return myData.getData();
}, function (data) {
    console.log(data);
});

2) 观看对 myData 的引用$scope 上的服务内部数组:
$scope.myData = myData.getData();
$scope.$watch('myData', function (data) {
    console.log(data);
});

关于angularjs - 在 Controller AngularJS 之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32652142/

相关文章:

javascript - 将具有键的数组与对象 JavaScript 中的键进行比较

AngularJS UI 路由器 : Get the absolute URL of the state with the parameters

node.js - Angular 导入 Node 包

javascript - 获取 AngularJS 中最后一列的不同总计

AngularJS 从服务器加载数据

javascript - 如何从另一个angularjs刷新一个 Controller 的计数器值

javascript - 操作 promise 结果中的数据

javascript - Angular : some help understanding service/factory

javascript - 让 Angular 检测 $scope 中的变化

javascript - 如果失败但使用不同的参数来获取默认数据,则调用相同的 http 请求