我正在显示数据库中的所有文章,并且我已经为它创建了一个简单的文本搜索。
<input ng-model="searchText" placeholder="Search for articles" class="search-text">
我正在过滤searchText中的内容
<section class="articles" ng-repeat="contentItem in content | filter:searchText">
现在我正在尝试的是从我的数据库中获取带有类别和标签的按钮,并能够根据按钮值过滤内容。
<span ng-repeat="category in categories">
<button ng-click="searchText = '{{category.local.name}}'" class="btn btn-primary">{{ category.local.name }}</button>
</span>
上面的代码不起作用,但是例如,如果我取出ng-repeat并自己键入所有类别,它将起作用:
<span>
<button ng-click="searchText = 'some text'" class="btn btn-primary">Some text</button>
</span>
我的问题是如何将搜索输入和按钮中的内容传递给过滤方法?
以下是完整代码:
<div class="container">
<h1>List of articles</h1>
<section class="search-items">
<input ng-model="searchText" placeholder="Search for articles" class="search-text">
<div class="row">
<div class="col-sm-6">
<h6>Search based on categories:</h6>
<span ng-repeat="category in categories">
<input type="button" ng-click="searchText = '{{ category.local.name }}'" value="{{ category.local.name }}" class="btn btn-primary">
</span>
</div>
<div class="col-sm-6">
<h6>Search based on tags:</h6>
<span ng-repeat="tag in tags">
<input type="button" ng-click="searchText = '{{tag.local.name}}'" value="{{ tag.local.name }}" class="btn btn-primary">
</span>
</div>
</div>
</section>
<section class="articles" ng-repeat="contentItem in content | filter:searchText">
<article class="well">
<h3>{{ contentItem.local.title }}</h3>
<p>{{ contentItem.local.content }}</p>
<span><b>Article author: {{ contentItem.local.author }}</b></span><br/>
<span class="label label-primary">{{ contentItem.local.categories.category }}</span>
<span class="label label-primary">{{ contentItem.local.tags.tag }}</span>
</article>
</section>
</div>
答案 0 :(得分:0)
angular.module('myApp', [])
.controller('ThingsController', function(){
var ctrl = this;
ctrl.things = ['thing 1', 'thing 2', 'another thing']
ctrl.searchText = "something"
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ThingsController as thingCtrl">
<div ng-repeat="thing in thingCtrl.things">
<button ng-click="thingCtrl.searchText = thing">{{thing}}</button>
</div>
<pre>{{thingCtrl.searchText}}
&#13;
上面的代码段显示它也使用控制器作为语法。通常,您不希望使用$ scope,就好像它是您希望它指向模型的模型一样,否则您可能会遇到一些奇怪的原型继承问题。与使用控制器作为语法的$scope.myModel = {someProp:4}
而不是$scope.someProp = 4
一样,也避免了这个问题。
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?