2016-10-16 3 views
0

私はAngularJSアプリケーションを構築しています。私はこの配列を持っています:フレーズ内の単語の角フィルタ

$scope.products = [ 
    {name: 'cake (just it!)'}, 
    {name: 'orange cake'}, 
    {name: 'cheesecake'} 
]; 

次に、私はそれを表示するためにng-repeatを使います。

私はこれを行うのであれば、フレーズ内の各単語の先頭を検索するフィルタを追加したい
<li ng-repeat="product in products | filter : { name : word }"> 
    {{ $product.name }} 
</li> 

$scope.products = [ 
    {name: 'cake (just it!)'}, 
    {name: 'orange cake'} 
]; 

$scope.word = 'ca'; 

をそれは次の配列を返します。

+0

カスタムフィルタを作成して、内部で同じロジックを書き込んでください –

答えて

1

下記のようにカスタムフィルタを使用することができます。

var app = angular.module("sampleApp", []); 
 
app.controller("sampleController", ["$scope", 
 
    function($scope) { 
 
    $scope.products = [{ 
 
     name: 'cake (just it!)' 
 
    }, { 
 
     name: 'orange cake' 
 
    }, { 
 
     name: 'cheesecake' 
 
    }, { 
 
     name: 'cheese' 
 
    }, { 
 
     name: 'cheeseca ca' 
 
    }]; 
 

 
    } 
 
]); 
 

 
app.filter("nameFilter", function() { 
 

 
    return function(names, contains) { 
 
    return names.filter(function(obj) { 
 
     var expString = '(\\w*\\s|^)' + contains + ''; 
 
     var exp = new RegExp(expString, "g"); 
 

 
     if (exp.test(obj.name)) 
 
     return name; 
 
    }); 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="sampleApp"> 
 
    <div ng-controller="sampleController"> 
 
    <ul> 
 
     <li ng-repeat="product in products | nameFilter : 'ca' "> 
 
     {{product.name}} 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</div>

関連する問題