[英]strict mode filter in angularjs
当用户输入带有前缀“!”的字符串时,我只是想将严格过滤器作为一个选项实现 否则是普通过滤器
这就是我所做的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>
但是它不起作用。
为什么?
我该如何运作呢?
尝试这个:
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>
过滤器表达式有点复杂。 最好使用将由$ watch更新的中间变量在控制器中移动thos表达式:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.