簡體   English   中英

如何使用angular用json數據填充表?

[英]How to populate table with json data using angular?

我已經通過http成功加載了json數據,但是在基於輸入的值'name'填充此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>

試試這個,問題是在json文件中,entertedValue(在這種情況下為某人的名字)不是對象中的有效鍵,因此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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM