简体   繁体   中英

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. If I manually type "foo" into the input field, the table will filter for "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. 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

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

The link is a working example of the "proper" way to go about it.

http://plnkr.co/edit/EyV1R4WUyu2TEMTue3jT

If you are using ng-model then you shouldn't set your value in html. Instead you should be setting you model value in Angular. So get rid of you value="foo" and do this.

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 
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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