【问题标题】:Unable to generate angularjs table with ng-repeat in controller?无法在控制器中使用 ng-repeat 生成 angularjs 表?
【发布时间】:2017-09-26 11:57:00
【问题描述】:

我有以下示例 sn-p。我想通过ng-repeat 在角度表中显示我下面的json 对象,这是我从angular controller 脚本生成的。我已经完成了以下操作,但我不确定为什么表格没有生成并且它的数据没有显示。请让我知道,我不确定这里有什么问题。 Fiddle 可用。

需要得到类似的输出:

Text  IND   US    UK    AUS
No    100   200   170   50 

html:

<div ng-controller="TestCtrl">   
</div>

app.js:

var testmodule = angular.module('myModule', []);
testmodule.controller('TestCtrl', function ($scope) {
  $scope.mydata =  [{
    "a": ["IND", "US", "UK", "AUS"],
    "b": ["100", "200", "170", "50"],
    "c": "Text",
    "d": "No",
}];

var mytable= angular.element(' <div class="table-responsive"> <table class="table" ng-repeat="item in mydata track by $index"> <thead> <tr> <td>{{item.c}}</td><td ng-repeat="c1 in item.a track by $index">{{c1}}</td></tr></thead> <tbody> <tr> <td>{{p.d}}</td><td ng-repeat="d1 in p.b track by $index">{{d1}}</td></tr></tbody> </table> </div>');
console.log("mytable: "+JSON.stringify(mytable));
});

【问题讨论】:

  • 您希望 console.log 是什么样的?

标签: javascript angularjs json angularjs-ng-repeat


【解决方案1】:

首先,我将 html 放在 html 页面上,而不是作为控制器中的元素。其次,您试图访问p.dp.b,但这些字段位于您的ng-repeat 中的item 中(所以应该是item.ditem.b。看起来这样可以:

HTML:

<div ng-controller="TestCtrl">   
  <div class="table-responsive"> 
      <table class="table" ng-repeat="item in mydata track by $index"> 
        <thead> 
          <tr> 
            <td>{{item.c}}</td>
            <td ng-repeat="c1 in item.a track by $index">{{c1}}</td>
          </tr>
        </thead> 
        <tbody> 
          <tr> 
            <td>{{item.d}}</td>
            <td ng-repeat="d1 in item.b track by $index">{{d1}}</td>
          </tr>
        </tbody> 
      </table>
  </div>
</div>

JavaScript:

var testmodule = angular.module('myModule', []);
testmodule.controller('TestCtrl', function ($scope) {
  $scope.mydata =  [{
    "a": ["IND", "US", "UK", "AUS"],
    "b": ["100", "200", "170", "50"],
    "c": "Text",
    "d": "No",
}];

});

工作插件:HERE

-

更新: 看起来您想将角度元素输出到控制台,您应该知道 mytable 是角度元素而不是 json 对象,因此 您将无法对其进行字符串化...

【讨论】:

  • 感谢您的回复,但我可以在 html 中生成相同的内容,但我只需要在控制器中生成相同的内容,而不是像上面那样在 html 中生成。
  • @Sana 你的问题很有误导性,你说I have done the below, but I am not sure why table is not generating and it's data is not showing... 然后你说Need to get output(然后你显示我提供的输出)。你想达到什么目的?看来我的回答解决了问题...
  • 我只需要从控制器脚本生成类似上表的输出,我不应该在 html 文件中写入任何内容。
  • @Sana 您为什么不直接设置您的 myData 以便您可以执行 ng-repeat(a 是第一行,b 是第二行)?
  • 这看起来不错。但实际上我只想在控制器中生成与角度元素相同的内容。在 console.log 中,我可以看到带有 angular 元素的生成表。如果我在任何地方错了,我很抱歉。提前致谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多