我只想在用户输入前缀为“!”的字符串时将严格过滤器作为选项实现。否则正常过滤器
这就是我所做的 http://plnkr.co/edit/QaroPDzQxeLNjt4vZgRb?p=preview
脚本:
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.filter = { friends : [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}] };
$scope.opt = {
strict : false,
val : ''
};
}]);
html:
<form name="testForm" ng-controller="ExampleController">
<input ng-model="opt.val" placeholder="prefix ! for strict" ng-value="opt.val.substring(1)" class="my-input" />
<input type="checkbox" style="display:none;" ng-model="opt.strict" ng-bind="opt.strict" ng-checked="opt.val.chatAt(0)==='!'" class="my-input" />
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in filter.friends | filter:opt.val:opt.strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</form>
但它不起作用。
为什么?
我如何让它发挥作用?
答案 0 :(得分:1)
试试这个:
http://plnkr.co/edit/Q69RN3OnwxeSRKdYexEw?p=preview
<form name="testForm" ng-controller="ExampleController">
<input ng-model="opt.val" placeholder="prefix ! for strict" class="my-input" />
<input type="checkbox" style="display:none;" ng-model="opt.strict" ng-bind="opt.strict" ng-checked="opt.val.chatAt(0)==='!'" class="my-input" />
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in filter.friends | filter:(opt.val[0] === '!' ? opt.val.substring(1) : opt.val):(opt.val[0] === '!')">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</form>
过滤器表达式有点复杂。最好在控制器中移动thos表达式,使用可由$ watch更新的中间变量:
http://plnkr.co/edit/6w8mGsVtV50jv6mJdN6X?p=preview
JS:
$scope.opt = {
strict : false,
val: '',
fullVal : ''
};
$scope.$watch('opt.fullVal', function (value) {
$scope.opt.val = value[0] === '!' ? value.substring(1) : value;
$scope.opt.strict = value[0] === '!';
});
HTML:
<form name="testForm" ng-controller="ExampleController">
<input ng-model="opt.fullVal" placeholder="prefix ! for strict" class="my-input" />
<input type="checkbox" style="display:none;" ng-model="opt.strict" ng-bind="opt.strict" ng-checked="opt.val.chatAt(0)==='!'" class="my-input" />
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in filter.friends | filter:opt.val:opt.strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</form>