2015-04-02 54 views
0

我試圖通過點擊一個按鈕更新過濾下拉(組合框)模型。模型值正在改變,但下拉菜單仍然顯示一個空的選定選項。如果我刪除過濾器一切正常(當然沒有過濾)。角度過濾下拉模型沒有更新

Plunker:http://plnkr.co/edit/a48JSEiiATrkcQKxfJjx?p=preview

JS:

$scope.tasks = [ 
    {name:'Task1', taskid: 1, custid: 2}, 
    {name:'Task2', taskid: 2, custid: 2}, 
    {name:'Task3', taskid: 3, custid: 3} 
    ]; 

    $scope.myinfo = {}; 
    $scope.updateinfo = {name:'Cust Name', custid: 3, taskid: 3}; 

    $scope.setMyinfo = function(){ 
    $scope.myinfo = $scope.updateinfo; 
    }; 
}); 

app.filter('taskFilter', function() { 
    return function(input, criteria) { 
    var result = []; 
    for (var i = 0; i < input.length; i++) { 
     if(input[i].custid == criteria || input[i].custid === undefined){ 
      result.push(input[i]); 
     } 
    } 
    return result; 
    } 

HTML:

<button ng-click="setMyinfo()">Button</button> 
    <br> <br> 
    Filtered: 
    <select ng-model="myinfo.taskid"> 
     <option>---</option> 
     <option ng-repeat="task in tasks | taskFilter:myinfo.custid" value="{{task.taskid}}">{{task.name}}</option> 
    </select> 

    Unfiltered: 
    <select ng-model="myinfo.taskid"> 
     <option>---</option> 
     <option ng-repeat="task in tasks" value="{{task.taskid}}">{{task.name}}</option> 
    </select> 

    <br><br> 
    Value: {{myinfo.taskid}} 

感謝您的幫助!

回答

0

預過濾器列表中的鍵和值:

<div ng-repeat="(k,v) in filterCustId(tasks)"> 
    {{k}} {{v.pos}} 
</div> 

並基於控制器:

$scope.filterCustId = function(items) { 
    var result = {}; 
    angular.forEach(items, function(value, key) { 
     if (!value.hasOwnProperty('custid')) { 
      result[key] = value; 
     } 
    }); 
    return result; 
} 

來源: https://stackoverflow.com/a/14789258/4668696

+0

最好是在控制器中還是在視圖中過濾?控制器中的 – gerl 2015-04-02 13:18:47

+0

過濾器。即使它像http://jsfiddle.net/gerlstar/m9jecbay/3/這樣簡單的過濾,你也不應該在視圖@gerl – 2015-04-02 16:04:03

+0

中有任何邏輯? – gerl 2015-04-02 17:50:59

0

請以下行

if(input[i].custid == criteria || input[i].custid === undefined){ 
更新代碼

by

if(input[i].custid == criteria || input[i].custid === undefined || criteria == undefined){