使用Angular搜索JSON

时间:2016-06-16 19:59:17

标签: javascript html angularjs json

我正在尝试使用Angular搜索JSON。我已经在网上找到了几个关于如何做到这一点的教程,但我现在陷入困境并且无法知道我的问题是什么。我已尝试在Chrome中使用调试器,它似乎完全通过了JS,但没有显示任何内容。

我是初学者,如果我有一些明显的错误,请原谅我。

这是我的代码

HTML:

<!DOCTYPE html>
<!doctype html>
<html ng-app="spellSearch">
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="spellSearch.js"></script>
  </head>
  <body>
    <div ng-controller="spellSearchCtrl">
      <label>Name:</label>
      <input type="text" ng-model="searchString" placeholder="Enter any spell information">
        <ul ng-repeat="i in jsonSpellData | filter:searchString">
          <li>
          Name: {{i.name}} <br>
          Description: {{i.desc}} <br>
          Page Number: {{i.page}} <br>
          Range: {{i.range}} <br>
          Components: {{i.components}} <br>
          Material: {{i.material}} <br>
          Ritual: {{i.ritual}} <br>
          Duration: {{i.duration}} <br>
          Concentration: {{i.concentration}} <br>
          Casting Time: {{i.casting_time}} <br>
          Level: {{i.level}} <br>
          School: {{i.school}} <br>
          Class: {{i.class}}
        </li>
        </ul>
    </div>
  </body>
</html>

的JavaScript

var app = angular.module('spellSearch', []);

app.controller('spellSearchCtrl', function($scope, $http){
    $http.get('spells.json').success(function(data, status, headers, config){
        $scope.items = data.data;
    }).error(function(data, status, headers, config){
        console.log("No data found...");
    });
});

app.filter('searchFor', function(){
    return function(arr, searchString){
        if(!searchString){
            return arr;
        }
        var result = [];
        searchString = searchString.toLowerCase();
        angular.forEach(arr, function(item){
            if(item.name.toLowerCase().indexOf(searchString) !== -1){
                result.push(item);
            }
            else {
                result.push("No results.");
            }
        });
        return result;
    };
});

JSON的一部分

var jsonSpellData = [
  {
    "name":"Abi-Dalzim's Horrid Wilting",
    "desc":"<p>You draw the moisture from every creature in a 30-foot cube centered on a point you choose within range. Each creature in that area must make a Constitution saving throw. Constructs and undead aren't affected, and plants and water elementals make this saving throw with disadvantage. A creature takes 10d8 necrotic damage on a failed save, or half as much damage on a successful one.You hurl a bubble of acid. Choose one creature within range, or choose two creatures within range that are within 5 feet of each other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.</p><p>This spells damage increases by 1d6 when you reach 5th Level (2d6), 11th level (3d6) and 17th level (4d6).</p>",
    "page":"ee pc 15",
    "range":"150 feet",
    "components":"V, S, M",
    "material":"A bit of sponge.",
    "ritual":"no",
    "duration":"Instantaneous",
    "concentration":"no",
    "casting_time":"1 action",
    "level":"8th-level",
    "school":"Necromancy",
    "class":"Sorcerer, Wizard"
  },
  {
    "name":"Absorb Elements",
    "desc":"<p>The spell captures some of the incoming energy, lessening its effect on you and storing it for your next melee attack. You have resistance to the triggering damage type until the start of your next turn. Also, the first time you hit with a melee attack on your next turn, the target takes an extra 1d6 damage of the triggering type, and the spell ends.</p>",
    "higher_level":"<p>When you cast this spell using a spell slot of 2nd level or higher, the extra damage increases by 1d6 for each slot level above 1st.</p>",
    "page":"ee pc 15",
    "range":"Self",
    "components":"S",
    "ritual":"no",
    "duration":"1 round",
    "concentration":"no",
    "casting_time":"1 action",
    "level":"1st-level",
    "school":"Abjuration",
    "class":"Druid, Ranger, Wizard"
  }
];

2 个答案:

答案 0 :(得分:1)

您可以直接在ng-repeat内过滤数据。 只需完全删除自定义过滤器。

您还可以添加ng-if =“searchString”,以便只显示已过滤的法术。

  <input type="text" ng-model="searchString" placeholder="Enter any spell information">
    <ul ng-if="searchString" ng-repeat="i in spell.jsonSpellData | filter:searchString">
      <li>
        Name: {{i.name}}
      </li>
    </ul>

function spellSearchCtrl() {
  this.jsonSpellData = [ { "name":"Abi-Dalzim's Horrid Wilting" }, { "name":"Absorb Elements" } ];
}
angular.module('myApp', []);
angular
    .module('myApp')
    .controller('spellSearchCtrl', spellSearchCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="spellSearchCtrl as spell">
      <label>Name:</label>
      <input type="text" ng-model="searchString" placeholder="Enter any spell information">
        <ul ng-if="searchString" ng-repeat="i in spell.jsonSpellData | filter:searchString">
          <li>
            Name: {{i.name}}
          </li>
        </ul>
    </div>
</div>

答案 1 :(得分:1)

随时用你的json验证你的json https://jsonformatter.curiousconcept.com/
从JSON文件中删除赋值和分号。

[
  {
    "name":"Abi-Dalzim's Horrid Wilting",
    "desc":"<p>You draw the moisture from every creature in a 30-foot cube centered on a point you choose within range. Each creature in that area must make a Constitution saving throw. Constructs and undead aren't affected, and plants and water elementals make this saving throw with disadvantage. A creature takes 10d8 necrotic damage on a failed save, or half as much damage on a successful one.You hurl a bubble of acid. Choose one creature within range, or choose two creatures within range that are within 5 feet of each other. A target must succeed on a Dexterity saving throw or take 1d6 acid damage.</p><p>This spells damage increases by 1d6 when you reach 5th Level (2d6), 11th level (3d6) and 17th level (4d6).</p>",
    "page":"ee pc 15",
    "range":"150 feet",
    "components":"V, S, M",
    "material":"A bit of sponge.",
    "ritual":"no",
    "duration":"Instantaneous",
    "concentration":"no",
    "casting_time":"1 action",
    "level":"8th-level",
    "school":"Necromancy",
    "class":"Sorcerer, Wizard"
  },
  {
    "name":"Absorb Elements",
    "desc":"<p>The spell captures some of the incoming energy, lessening its effect on you and storing it for your next melee attack. You have resistance to the triggering damage type until the start of your next turn. Also, the first time you hit with a melee attack on your next turn, the target takes an extra 1d6 damage of the triggering type, and the spell ends.</p>",
    "higher_level":"<p>When you cast this spell using a spell slot of 2nd level or higher, the extra damage increases by 1d6 for each slot level above 1st.</p>",
    "page":"ee pc 15",
    "range":"Self",
    "components":"S",
    "ritual":"no",
    "duration":"1 round",
    "concentration":"no",
    "casting_time":"1 action",
    "level":"1st-level",
    "school":"Abjuration",
    "class":"Druid, Ranger, Wizard"
  }
]

HTML文件

<html ng-app="spellSearch">
  <head>
    <meta charset="utf-8">
    <title>Angular.js JSON Fetching Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
    var app = angular.module('spellSearch', []);
      app.controller('spellSearchCtrl', function ($scope, $http){
        $http.get('spells.json').success(function(data) {
          $scope.spells = data;
        });
      });  
    </script>
  </head>
  <body ng-controller="spellSearchCtrl">
    <h2>Angular.js JSON Fetching Example</h2>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="searchString" placeholder="Enter any spell information">
        <ul ng-repeat="i in spells | filter:searchString">
          <li>
          Name: {{i.name}} <br>
          Description: {{i.desc}} <br>
          Page Number: {{i.page}} <br>
          Range: {{i.range}} <br>
          Components: {{i.components}} <br>
          Material: {{i.material}} <br>
          Ritual: {{i.ritual}} <br>
          Duration: {{i.duration}} <br>
          Concentration: {{i.concentration}} <br>
          Casting Time: {{i.casting_time}} <br>
          Level: {{i.level}} <br>
          School: {{i.school}} <br>
          Class: {{i.class}}
        </li>
        </ul>
    </div>
  </body>
</html>