问题
I'm trying to make a searchable list of posts on a ruby on rails application that I made. I have AngularJS working on the application. All of the posts are saved on rails in @posts. How would I make AngularJS filter over that? Here is the relevant view:
<h1>Posts</h1>
<div ng-app>
<div ng-controller = "PostCtrl">
<input placeholder = "Search Post Titles", ng-model="searchText">
<div ng-repeat="post in posts | filter:searchText">
<h2>{{post.title}}</h2>
<p>{{post.text}}</p>
</div>
</div>
</div>
I'm not sure how to fill the angular array posts with the objects in @posts.
回答1:
It appears that your code works as it is. Here is a plunker that seems to recreate your code.
If you would like to filter inside the post object, you can use this syntax:
ng-repeat="post in posts | filter:{ text: searchText }"
The above will only search the values of the text property of post.
回答2:
Continuing the answer of Davin Tryon, you can try as this. First use ng-init="init()" in your Controller:
<div ng-controller = "PostCtrl" ng-init="init( <%= @posts.to_json %> )">
Then in your controller you can do:
$scope.init = (posts) ->
$scope.posts = angular.fromJson(posts)
Then posts will be a JavaScript Object which can be accessed in your scope as if you have query it using angular resource.
If you want to include the associations of posts (lets say comments i.e) you can check rails docs for to_json (or "as_json") and the :include option
来源:https://stackoverflow.com/questions/19848283/angularjs-filter-in-rails