Eel*_*lco 5 angularjs angularjs-service
我正在尝试向控制器1发送一个充满对象的数组到控制器2.但是我在控制器2中得到的只是一个空数组.我得到一个填充的唯一方法是在我的服务中创建一个静态数组.
我的服务
app.service('myData', function () {
this.myData = [];
this.addData = function(data) {
this.myData.push(data);
}
this.getData = function() {
return this.myData;
}});
Run Code Online (Sandbox Code Playgroud)
控制器1设置数据
app.controller('controller1',['$scope', 'myData', function($scope, myData) {
$scope.addData = function(index, name) {
myData.addData({index: index, name: name});
}}]);
Run Code Online (Sandbox Code Playgroud)
控制器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);}]);
Run Code Online (Sandbox Code Playgroud)
当我在寻找答案时,我发现了很多类似于我的问题.唯一的区别是我从控制器填充我的服务而不是创建静态服务.
我的console.logs都返回一个空数组.为什么是这样?
您的$watch表达式应该是一个函数(请参阅文档$watch)。给出$watch一个字符串告诉 Angular 检查$scope. 除此之外,您还错误地将您的myData服务引用为字符串中的“数据” 'data.getData()'。
1)观察结果myData#getData:
$scope.$watch(function () {
return myData.getData();
}, function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
myData2) 观察对服务内部数组的引用$scope:
$scope.myData = myData.getData();
$scope.$watch('myData', function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |