简体   繁体   English

将输入字段用于AngularJS的默认过滤器和用户定义的过滤器

[英]Using input field for both default and user-defined filter with AngularJS

There must be a simple answer to this, but I'm not getting it. 对此必须有一个简单的答案,但我不明白。 I'm using the following input element to filter the results in a table through AngularJS. 我正在使用以下输入元素通过AngularJS将结果过滤到表中。 If I manually type "foo" into the input field, the table will filter for "foo". 如果我在输入字段中手动键入“ foo”,则表将过滤“ foo”。 But my hard-coded value of "foo" (in the input's value attribute) will neither show up in the browser nor filter the results upon page load. 但是我的硬编码值“ foo”(在输入的value属性中)既不会显示在浏览器中,也不会在页面加载时过滤结果。 How can I make this input field provide both a default filter and a user-defined filter? 如何使此输入字段提供默认过滤器和用户定义的过滤器? Thanks in advance. 提前致谢。

<input ng-model="search" id="search" type="text" placeholder="Search" value="foo">
<div ng-controller="eventsController")>
    <table>
        <tr ng-repeat="event in events | filter:search">
            <td><span ng-bind="event.title"></span></td>
            <td><span ng-bind="event.date_start"></span></td>
        </tr>
    </table>
</div>
<script>
    function EventsController($scope, $http) {
        $http.get('/api/all-events').success(function(events) {
            $scope.events = events;
        });
    }
</script>

Edited, initial response is an option but not recommended. 编辑过的初始响应是一个选项,但不建议使用。

According to the documentation for ng-init 根据ng-init的文档

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. ngInit的唯一适当用法是为ngRepeat的特殊属性添加别名,如下面的演示所示。 Besides this case, you should use controllers rather than ngInit to initialize values on a scope. 除了这种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。

The link is a working example of the "proper" way to go about it. 该链接是解决此问题的“正确”方法的有效示例。

http://plnkr.co/edit/EyV1R4WUyu2TEMTue3jT http://plnkr.co/edit/EyV1R4WUyu2TEMTue3jT

If you are using ng-model then you shouldn't set your value in html. 如果您使用的是ng-model,则不应在html中设置值。 Instead you should be setting you model value in Angular. 相反,您应该在Angular中设置模型值。 So get rid of you value="foo" and do this. 因此,摆脱掉您value =“ foo”并执行此操作。

function EventsController($scope, $http) {
        $http.get('/api/all-events').success(function(events) {
            $scope.events = events;
            $scope.search = "foo"; //This will set the models search to foo 
        });
    }

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

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