我正在尝试创建一个显示下面模板的指令,并最终允许轻松过滤。选择选择列表上的选项并在输入框中输入值时,模型将更改。我需要指令来包含这个模型,然后使用模型进行过滤。
到目前为止,{p> This已经到了目前为止。任何人都可以给我一些指导,因为我很确定我的例子中也有多余的代码。<div ng-controller="resultsCtrl">
<div ng-controller="searchFilterCtrl">
<dynamic-filters dynamic-filters-directive-search="getSearchFilters"></dynamic-filters>
</div>
<div ng-repeat="person in persons | filter: search">
{{person.name}}
</div>
模板:
<select ng-model="filterType">
<option value="age">Age</option>
<option value="customerId">CustomerID</option>
<option value="productId">ProductID</option>
</select>
<input type="text" name="select-option-value" ng-model="search[filterType]">
<p>You want to filter the field : {{filterType}}</p>
答案 0 :(得分:1)
我认为你很接近,但实际上更简单。试试this
索引HTML:
<div ng-controller="resultsCtrl">
<dynamic-filters search="search"></dynamic-filters>
<div ng-repeat="person in persons | filter: search">
{{person.name}}
</div>
</div>
指令HTML:
<select ng-model="filterType">
<option value="age">Age</option>
<option value="customerId">CustomerID</option>
<option value="productId">ProductID</option>
<option value="name">Name</option>
</select>
<input type="text" name="select-option-value" ng-model="search[filterType]">
<p>You want to filter the field : {{filterType}}</p>
script.js JS代码:
angular.module('app', ['dynamicFiltersDirective']).controller('resultsCtrl', function($scope){
$scope.persons = [{
name: 'Jim',
age: 18,
customerId: 1,
productId: 4
},{
name: 'Frank',
age: 20,
customerId: 2,
productId: 5
},{
name: 'Bob',
age: 20,
customerId: 3,
productId: 5
}];
});
指令JS代码:
angular.module('dynamicFiltersDirective', [])
.directive('dynamicFilters', function() {
return {
restrict: 'AE',
scope: {
search: '='
},
link: function(scope) {
scope.$watch('filterType', function(v) {
if(!v) {return;}
//clear out the search
scope.search = {};
scope.search[v] = '';
});
},
templateUrl: 'filtertemplate.html'
}
});