2014-12-03 13 views
1

我確信這並不難,但如果任何人都可以幫助我。ng-submit通過ng-model輸入過濾ng-repeat

here is a plnkr

<form ng-submit="submit()"> 
    <input ng-model="query"> 
    <button type="submit" id="submit" value="Submit" >Search</button> 
</form> 


<div ng-repeat="x in friends | filter:query"> 
    {{x.name}} 
</div> 

我要過濾提交我猜它可能是用做搜索,而不是動態類型或者NG單擊或NG提交。只是一個很好的做法。

回答

6

試試這個代碼,看下面的輸出。

首先,您需要在作用域上設置另一個變量並通過該變量進行過濾,在submit()上使查詢模型的值等於作用域上的「q」變量,並將相應地過濾爲過濾條件爲「 q」現在

var app = angular.module('myapp', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.q=""; 
 
    
 
    $scope.submit=function(){ 
 
     $scope.q= $scope.query 
 
    } 
 
    $scope.friends = [ 
 
    { 
 
     id: 1, 
 
     name: "Sarah" 
 
    }, 
 
    { 
 
     id: 2, 
 
     name: "Joanna" 
 
    }, 
 
    { 
 
     id: 3, 
 
     name: "Heather" 
 
    }, 
 
    { 
 
     id: 4, 
 
     name: "Kim" 
 
    } 
 
    ]; 
 
    
 

 
});
<!DOCTYPE html> 
 
<html ng-app="myapp"> 
 

 
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script> 
 
    document.write('<base href="' + document.location + '" />'); 
 
    </script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="http://code.angularjs.org/1.2.7/angular.js" data-semver="1.2.7"></script> 
 
    <script src="app.js"></script> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 

 
    <form ng-submit="submit()"> 
 
    <input ng-model="query"> 
 
    <button type="submit" id="submit" value="Submit">Search</button> 
 
    </form> 
 

 

 
    <div ng-repeat="x in friends | filter:q"> 
 
    {{x.name}} 
 
    </div> 
 
</body> 
 

 
</html>

+0

甜!我喜歡這樣做的方式。謝謝! – user3224271 2014-12-03 20:27:00

+0

我的榮幸,很高興聽到它:) – 2014-12-03 20:28:14

0

您可以輕鬆地Angular.js 1.3.x的採用NG-模型選擇實現這個...

<form ng-submit="submit()"> 
    <input ng-model="query" ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"> 
    <button type="submit" id="submit" value="Submit" >Search</button> 
</form> 

http://plnkr.co/edit/9JHnSXAldpm7Yb9Bl2gC?p=preview

它允許您自定義延遲,而不是在鍵入時立即執行,但它不在提交。