【问题标题】:how can i access array elements in a $scope variable angular js from php?如何从 php 访问 $scope 变量 angular js 中的数组元素?
【发布时间】:2017-05-25 04:35:42
【问题描述】:

我在 php 中创建了一组卡片:

$card = array(
      "id" => $row["id"],
      "nome" => $row["nome"],
      "indirizzo" => $row["indirizzo"],
      "descrizione" => $row["descrizione"],
      "prezzo" => $row["prezzo"],
      "images" => array(),
      "thumbs" => array(),
      "dataInserimento" => $row["inserimento"],
      "dataModifica" => $row["modifica"],
      "bigImage" => array(),
      "lat" => $row["lat"],
      "lng" => $row["lng"],
      "latInd"=>$row["latInd"],
      "lngInd"=>$row["lngInd"]);

在一个循环中我这样做:

 $cards["card"][] = $card;

然后我将数据传递给 angular:

回显 json_encode($cards);

在控制器中,我将数组复制到范围变量中:

  $scope.cards=[];
  CardService.getCards($scope.lastCard).then(function (success) {
    CardService.setLocalCards(success.data.card);
    /*check if all imges are loaded*/
    for (var i = 0; i < success.data.card.length; i++) {
      console.log(success.data.card);
      console.log("numero di card caricate " + success.data.card[i].id);
      var localCard = CardService.getLocalCard(success.data.card[i].id);
      if (localCard === null || localCard.photosLoaded === true) {
        $scope.cards.push((success.data.card[i]));
        $scope.lastCard = success.data.card[i].id;
      }
    }
    $ionicLoading.hide();
    console.log("ultima scheda caricata " + $scope.lastCard);
  }, function (fail) {
    console.log("getCards error " + JSON.stringify(fail));
  });
  console.log($scope.cards);

问题是,如果我尝试访问 $scope.cards 中的元素,我可以从 CardService 中的 then 函数访问它们,但在外部我得到了这个:

而且我不知道如何访问元素

【问题讨论】:

    标签: php angularjs json post ionic-framework


    【解决方案1】:

    由于您使用的是异步的 Promise,因此您的 console.log 将在 CardService.getCards 函数之后和 .then() 内的函数之前执行。 .then 中的函数是一个仅在 getCards 完成后执行的承诺。所以当你做console.log($scope.cards);The到达时它仍然是空的。

    无论哪种方式,请确保您实际上正在执行 $scope.cards 内的任何推送,并且您可以尝试在 promise 内执行 console.log($scope.cards)(在卡片被推送后)以查看它是否实际填充。

    【讨论】:

    • 我回答了我自己,感谢您的回答。问题是首先我填充卡片数组然后我更改页面,然后当我返回时我打印卡片并且是空的,因为卡片不是会话变量。但这很奇怪,因为当我打印卡片时我看到一个空数组,当我打开它时,我从控制台获取值,但无法从代码中访问它们。
    • 太棒了!可能最后一部分是因为当您在控制台上打印时它已被填充,但之后它被擦除,也许它没有正确保存在变量上以将其保留在 $scope 上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多