如何使用AngularJS过滤按钮中的第一个字母

时间:2015-03-24 03:38:57

标签: angularjs

如何使按钮起作用,并且按钮具有默认值,例如按钮A-B具有要过滤的第一个字母的a到b的范围。谢谢,对不起我的上一篇文章,很难理解。 =)



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

app.filter('startsWithLetter', function () {
    return function (items, letter) {
        var filtered = [];
        var letterMatch = new RegExp(letter, 'i');
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (letterMatch.test(item.name.substring(0, 1))) {
                filtered.push(item);
            }
        }
        return filtered;
    };
});

app.controller('PersonCtrl', function () {
    this.friends = [{
        name: 'Andrew'        
    }, {
        name: 'Baldo'
    }, {
        name: 'Carlo'
    }, {
        name: 'Delo'
    }, {
        name: 'Emman'
    }, {
        name: 'Ferman'
    }];
});
&#13;
</style>
<script src="//code.angularjs.org/1.3.0-beta.7/angular.js"></script>
<style>
&#13;
<div ng-app="app">
    <div ng-controller="PersonCtrl as person">
        <input type="text" ng-model="letter" placeholder="Enter a letter to filter">
        <button>A-B</button>
        <button>C-D</button>
        <button>E-F</button>
      
        <ul>
            <li ng-repeat="friend in person.friends | startsWithLetter:letter">
                {{ friend }}
            </li>
        </ul>
    </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这是你的意思吗?你想点击每个按钮来过滤这两个字母吗?

我所做的更改是将按钮的标记设置为:

<button ng-click="letter='[AB]'">A-B</button>
<button ng-click="letter='[CD]'">C-D</button>
<button ng-click="letter='[EF]'">E-F</button>

&#13;
&#13;
var app = angular.module('app', []);

app.filter('startsWithLetter', function () {
    return function (items, letter) {
        var filtered = [];
        var letterMatch = new RegExp(letter, 'i');
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (letterMatch.test(item.name.substring(0, 1))) {
                filtered.push(item);
            }
        }
        return filtered;
    };
});

app.controller('PersonCtrl', function () {
    this.friends = [{
        name: 'Andrew'        
    }, {
        name: 'Baldo'
    }, {
        name: 'Carlo'
    }, {
        name: 'Delo'
    }, {
        name: 'Emman'
    }, {
        name: 'Ferman'
    }];
});
&#13;
</style>
<script src="//code.angularjs.org/1.3.0-beta.7/angular.js"></script>
<style>
&#13;
<div ng-app="app">
    <div ng-controller="PersonCtrl as person">
        <input type="text" ng-model="letter" placeholder="Enter a letter to filter">
        <button ng-click="letter='[AB]'">A-B</button>
        <button ng-click="letter='[CD]'">C-D</button>
        <button ng-click="letter='[EF]'">E-F</button>
      
        <ul>
            <li ng-repeat="friend in person.friends | startsWithLetter:letter">
                {{ friend }}
            </li>
        </ul>
    </div>
</div>
&#13;
&#13;
&#13;