我可以在控制台中打印值,但不能在 html 视图中打印值

I can print the value in console but not in html view

本文关键字:打印 html 视图 但不能 我可以 控制台      更新时间:2023-09-26

我是角度js的新手。我正在尝试在下拉列表中显示数据,但输出来自控制台而不是 html 视图。

.html:-

 <select ng-model="billing.billing" ng-options="billing in billAddress track by $index">
 </select>
<p>{{billing.billing}}</p>

js 文件:

 appServices.getBillAddress(userData.customerId).then(function (data){
          if (data){  
                console.log(data);      
                $scope.addressToBill = data; 
                var billAddress=[];
                 //var billAddress=[];
                if ($scope.addressToBill){
                    storeLocally.set('shipInfo', $scope.addressToBill);
                    for(var i=0;i<data.length;i++){
                     $scope.city = $scope.addressToBill[i].city;
                     $scope.state = $scope.addressToBill[i].state;
                     $scope.country = $scope.addressToBill[i].country;
                     $scope.billAddress = $scope.city +", "+  $scope.state +", "+ $scope.country;
                     console.log("billing address test: " +$scope.billAddress);
                    } 
                   }
                }
            }         
 },
  function (data) {
      if (data.status == 500) {
        $scope.addressError = "Oops! No Address Found!";    
      };
});        

数据包含以下信息:

  [{city="fremont", country="USA", state="California"}]

我在控制台中收到错误:

账单地址测试:美国加利福尼亚州弗里蒙特

错误: [ngOptions:iexp] "选择(作为标签)"形式的预期表达式? for (key,)?收集值",但得到"账单地址中按$index跟踪计费"。

我不明白如何解决选择和ng选项错误。如果值出现在控制台上,那么为什么它没有显示在 html 下拉列表中。请帮帮我。

首先,你的$scope.billAddress应该是一个集合,而不是单个字符串。按如下方式重构代码:

.then(function(data){
  if (!data) {
    // handling this case may vary; here I just clear the collection
    $scope.billAddress = [];
    return;
  }
  storeLocally.set('shipInfo', data);
  $scope.billAddress = data.map(function(address) {
    return {
      billing: address.city + ', ' + address.state + ', ' + address.country
    };
  });
});

其次,您需要修复ng-options语法。一种可能的方法:

<select ng-model="selectedBilling" ng-options="billing.billing for billing in billAddress track by $index">
<p ng-bind="selectedBilling.billing"></p>

看起来您总是将其设置为列表中的最后一个。 不知道这是不是故意的..如果是这样,请告诉我。

但听起来您想在每个项目上设置账单地址,然后将其用作标签? 如果是这样,请在您的 for 循环数据中设置。billAddress = ... ,然后使用以下选择。

<select ng-model="selectedBilling" 
        ng-options="billing as billing.billingAddress for billing in billAddress track by $index">

 <p>{{selectedBilling}}</p>

此行不起作用:

<p>{{billing.billing}}</p>

因为p超出了select-> options的范围

只是一个片段来说明!

https://jsfiddle.net/alvarojoao/7wwdyymz/