项目添加到AngularJS承诺的数组 [英] Add an item to a promised array in AngularJS

查看:113
本文介绍了项目添加到AngularJS承诺的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用谁阿贾克斯获得对象数组的函数$ HTTP:

I have a function who get an array of objects by ajax using $http :

$scope.getArray = function(page) {
    return $http.get(page).then(function(data) {
        return data.data;
    });
};

我用这种方式:

$scope.array = $scope.getArray('somepage');

这code的实际工作,我有我想要在视图中的数据。

This code works actually and I have the data I want on the view.

不过,我想在这个数组的末尾添加一些数据。我试过

However, I want to add some data at the end of this array. I tried

$scope.addToArray = function(newItem) {
    $scope.array.push(newItem);
};

但是,这并不能正常工作。

But that didn't work.

任何想法如何做到这一点?谢谢你。

Any ideas how to do that ? Thanks.

推荐答案

看起来你是在虐待的承诺!

It looks like you are mistreating the promise!

如果您希望能够从返回的getArray,那么你不应该将承诺给你的范围变量的数据捣鼓。相反,改变工作的getArray方式:

If you want to be able to fiddle with the data returned from getArray then you shouldn't assign the promise to your scope variable. Instead, change the way getArray works:

$scope.getArray = function(page) {
    var propertyAccessor = $parse(page);
    return $http.get(page).then(function(data) {
        page.assign($scope, data.data);
    });
};

现在,当你调用get阵列,它将数据的数据加载到数据属性,你将能够修改(一旦它运行的第一次)

Now when you call get array, it will load the data data into the data property and you will be able to modify that (once it has run for the first time)

$scope.getArray('somepage');

$scope.addToArray = function(page, newItem) {
   var propertyAccessor = $parse(page);
   propertyAccessor($scope).push(newItem);
}

$scope.addToArray('somepage', 'someValue');

我把这个演示起来这里,它既有你原来implemnenation和我的工作示例(使用$ q模拟的)。

I put a demo of this together here, it has both your original implemnenation (simulated using $q) and my working example.

这篇关于项目添加到AngularJS承诺的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆