简体   繁体   English

如何在Angular中过滤数组?

[英]How to to filter the array in Angular?

When I input in the input, the ul only show the li which include my input.当我输入时,ul 只显示包含我输入的li For example, if I am inputting the"Ad", then only show the "Add some todos" li.例如,如果我输入“广告”,则只显示“添加一些待办事项”li。 And if I give up input, the ul will go back, and all the Li will show again.如果我放弃输入,ul 将返回,所有 Li 将再次显示。 How to realize It?如何实现它?

It is my code below.下面是我的代码。

<body>
<script src="angular.js"></script>
<div ng-controller="ctr1">
    <input ng-model='newTodo' type="text" ng-keyup="$event.keyCode == 13 && addTodo()">
    <ul>
        <li ng-repeat="todo in fillArray">
            <span>{{todo.text}}</span>
            <button ng-click="removeTodo($index)">X</button>
        </li>
    </ul>
</div>
<script>

    var app = angular.module("app",[]);
    var contrl = app.controller('ctr1',['$scope',function ($scope) {
        $scope.todos = [{text:"Add some todos"}];
        $scope.newTodo = '';
        $scope.addTodo = function () {
            var text = this.newTodo.trim();
            if(text){
                this.todos.push(
                        {text:text}
                );
                this.newTodo= '';
            }
        };
        $scope.removeTodo = function (index) {
            this.todos.splice(index,1);
        };

        $scope.fillArray =$scope.todos.filter(function (item) {
            return (item.text.toLocaleLowerCase().indexOf($scope.newTodo) > -1);});
    }]);

</script>
</body>

**How to get the fillArray? **如何获取fillArray? ** My code is wrong. ** 我的代码是错误的。

<body>
<div ng-controller="ctr1">
    <input ng-model='newTodo' type="text" ng-keyup="$event.keyCode == 13 && addTodo()">
    <ul>
        <li ng-repeat="todo in todos | filter : newTodo">
            <span>{{todo.text}}</span>
            <button ng-click="removeTodo($index)">X</button>
        </li>
    </ul>
</div>
<script>

    var app = angular.module("app",[]);
    var contrl = app.controller('ctr1',['$scope',function ($scope) {
        $scope.todos = [{text:"Add some todos"}];
        $scope.newTodo = '';
        $scope.addTodo = function () {
            var text = this.newTodo.trim();
            if(text){
                this.todos.push(
                        {text:text}
                );
                this.newTodo= '';
            }
        };
        $scope.removeTodo = function (index) {
            this.todos.splice(index,1);
        };


    }]);

</script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM