4

私はブログページを作成しようとしていますが、AngularJS ではなく WordPress を選択して、Google がページをインデックス化できるようにしました (または、少なくともそれが機能していると思います)。だから今のところ、私はこのようなリストを持っています

<ul>
    <li id="1">
        <h2>My first Post</h2>
        <p>The Message...</p>
    </li>
    <li id="2">
        <h2>My second Post</h2>
        <p>The Message...</p>
    </li>
    <li id="3">
        <h2>My third Post</h2>
        <p>The Message...</p>
    </li>
</ul>

PHPはかなり静的なので、投稿をタイトルでフィルタリングする角度フィルターを作成したいのですが、これを行う方法がよくわかりません。

アイテムの非表示クラスを作成し<li>、フィルターのために投稿を削除する必要がある場合は、非表示クラスを追加することを考えていました。この角度を混ぜて、検索後にページを再度ロードする代わりに動的検索を実行できるようにします。

4

3 に答える 3

3

JSON 形式の項目のみを返すサービスがないことを考えると、最良の方法は、 を削除しli、その内容をオブジェクトに解析しng-repeatてテンプレートで使用するディレクティブを作成することです。このようなもの:

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

app.directive('filtered', function() {
  return {
    scope: {
      criteria: '=filtered'
    },
    compile: function(elm, attr) {
      var entries = [];

      elm.find('li').each(function(index, item) {
        var entry;

        $item = angular.element(item);

        entries.push({
              id: $item.attr('id'),
          title: $item.find('h2').text(),
          body: $item.find('p').text()
        });
      }).remove();

      elm.append(
        '<li ng-repeat="entry in entries | filter:{title: criteria}" id={{entry.id}}>' +
          '<h2>{{entry.title}}</h2>' +
          '<p>{{entry.body}}</p>' +
        '</li>'
      );

      return function(scope) {
        scope.entries = entries;
      };
    }
  };
});

HTML では、次のディレクティブでリストを装飾するだけです。

<input ng-model="userCriteria">

<ul filtered="userCriteria">
  <li id="1">
    <h2>My first Post</h2>
    <p>The Message...</p>
  </li>
  <li id="2">
    <h2>My second Post</h2>
    <p>The Message 2...</p>
  </li>
  <li id="3">
    <h2>My third Post</h2>
    <p>The Message 3...</p>
  </li>
</ul>

ここに Plnkrをまとめました。HTML リストを変更すると、その項目が自動的に含まれます。

于 2013-10-02T17:34:22.550 に答える
0

JSON アプローチを使用できる場合は、Angular が自動的にそれを行います。

シンプルなフィルター ソリューションを使用するだけです。

<input ng-model="criteria"/>

<ul>
  <li ng-repeat="entry in entries | filter:{title: criteria}" id="{{entry.id}}">
    <h2>{{entry.title}}</h2>
    <p>{{entry.body}}</p>
  </li>
</ul>

コントローラー (またはコンテナー スコープにアクセスできる任意の JS) で:

app.controller('MainCtrl', function($scope) {
  $scope.criteria = "Title";

  $scope.entries = [
    {
      id: 1,
      title: 'My title',
      body: 'contents...'
    },
    {
      id: 2,
      title: 'The other content',
      body: 'contents...'
    },
    {
      id: 3,
      title: 'Another title',
      body: 'contents...'
    },
    {
      id: 4,
      title: 'Something completely different',
      body: 'contents...'
    }
  ];
});

$httpservice を使用して JSON ファイルを取得することもできます。

app.controller('MainCtrl', function($scope) {
  $scope.criteria = "Title";
  $scope.entries = $http.get('path/to/entries.json');
});
于 2013-10-02T15:00:43.960 に答える