【问题标题】:How to populate table with json data using angular?如何使用角度用 json 数据填充表?
【发布时间】:2015-09-04 14:28:55
【问题描述】:

我已通过 http 成功加载了 json 数据,但在根据输入的值“名称”使用此 json 数据填充表时出现问题。下面的小插曲。

Plunker

json

   [
    {
        "name": "Tim",
        "address": "Road",
        "phone": "1234",
        "status": "busy"
    },

    {
        "name": "Sue",
        "address": "Street",
        "phone": "4321",
        "status": "available"
    }
  ]

假设我的控制器和应用程序定义正确,我做错了什么?我想输入 Tim 或输入 Sue 并用相应的数据填充表格。

angular.js

 $http.get('data.json').
     success(function(data) {
      $scope.jsonData = data;
        alert("Success");
     }).
     error(function(data) {
        alert("Invalid URL");
   });

   $scope.clickButton = function(enteredValue) {

    $scope.items = $scope.jsonData;

    angular.forEach($scope.items[enteredValue], function (item, key) {
        $scope.results.push({
                 name: enteredValue,
                 address: item.address,
                 phone: item.phone, 
                 status: item.status
             });

 });

jsp

 <table>
        <tr>
            <td><label>Name:</label></td>
  <td>
    <input id="pName" name="pName" type="text" data-ng-model="enteredValue" /> 
            </td>
        </tr>

  <button class="btn btn-primary" data-ng-click='clickButton(enteredValue)'>Search</button>


 <table>
       <tr data-ng-repeat="result in results">
        <td data-title="'ID'">{{result.status}}</td>
        <td data-title="'Name'">{{result.name}}</td>
        <td data-title="'Status'" >{{result.address}}</td>
        <td data-title="'Start Date'" >{{result.phone}}</td>
      </tr>
 </table>

【问题讨论】:

    标签: javascript json angularjs angular-ngmodel


    【解决方案1】:

    试试这个,问题是在 json 文件中,enteredValue(在这种情况下是某人的名字)不是对象中的有效键,所以 angulars foreach 永远不会执行,因为你的 $scope.items[enteredValue] 总是未定义:

    $http.get('data.json')
    .success(function(data) {
        $scope.jsonData = data;
        alert("Success");
    })
    .error(function(data) {
        alert("Invalid URL");
    });
    
    $scope.clickButton = function(enteredValue) {
    
        $scope.items = $scope.jsonData;
    
        angular.forEach($scope.items, function (item) {
            if(item.name === enteredValue){
                $scope.results.push({
                    name: enteredValue,
                    address: item.address,
                    phone: item.phone, 
                    status: item.status
                });
            }
        });
    };
    

    我已经更新了你的 plunkr: http://plnkr.co/edit/YRo8SugTDQ54NIvUHDVy

    【讨论】:

    • 谢谢。做到了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 2015-12-20
    • 2018-12-27
    相关资源
    最近更新 更多