空角阵 [英] Empty angular array

查看:116
本文介绍了空角阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有复选框,这是动态地从的getJSON 要求建立的清单。

I have a list of checkboxes, which are dynamically built from getJson request.

<tr data-ng-repeat="(key, value) in relatedServices | orderBy:predicate:reverse | filter:search:strict">
 <td>
  <input type="checkbox" ng-model="array[$index]" ng-true-value="{{value.ID}}" ng-false-value="{{undefined}}" />
 </td>
<tr>

然后我想查一些复选框和 postJSON 他们。

下面是控制器code:

Here is controller code:

var myApp = angular.module('myApp', []);


    myApp.controller('JsonController', function ($http, $scope) {


        $http.get("/RS/GETJSON/")
        .success(function (response) {
            $scope.relatedServices = response;
        });

        $scope.array = [];

        var values = $scope.array;
        var log = [];

        angular.forEach(values, function (value, key) {
            this.push('{Id' + ': ' + value + '}');
        }, log);


        $scope.add = function () {
            $http.post("/RS/POSTJSON/", log);
        }

    });

问题是,当我检查复选框,值 $作用域 $ scope.array = [];

但是当我运行添加()登录= [] 都是空的。

But when I run add(), the log = [] are empty.

如何过,如果在脚本中我很难code值,可以说

How ever if I hardcode values in the script, lets say

$scope.array = ['1','2','3'];

此值不会消失。

我在做什么错了?

推荐答案

与code中的问题是时间,在$ http.get被调用,但一旦返回数据的成功只能部分调用。在此期间会继续执行,当你在foreach $ scope.array仍然是空的。您可以在foreach移动到add函数,但你也应该检查数据是否实际上已经归还。

The problem with your code is timing, the $http.get is called but the success part is only called once the data is returned. In the meantime execution continues and when you do the forEach $scope.array is still empty. You can move the forEach into the add function but you should also check to see if the data has actually been returned.

var myApp = angular.module('myApp', []);


myApp.controller('JsonController', function ($http, $scope) {

    var hasLoaded = false;

    $http.get("/RS/GETJSON/")
    .success(function (response) {
        $scope.relatedServices = response;
        hasLoaded = true;
   });

   $scope.array = [];

   $scope.add = function () {
       if(!hasLoaded) {
           alert('Still waiting');
           return;
       }

       var values = $scope.array;
       var log = [];

       angular.forEach(values, function (value, key) {
          this.push('{Id' + ': ' + value + '}');
       }, log);


       $http.post("/RS/POSTJSON/", log);
    }

});

这篇关于空角阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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