[英]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.