6

我正在使用UI-Select 0.8.4並且擁有大量數據集。然後我使用UI-Select在數據集旁邊的下拉列表中顯示屬性值。我正在使用這個過濾器。所以從下拉列表中選擇時,會過濾結果。ng-repeat不斷開火懸停

每當我將鼠標懸停在下拉菜單中的某個項目上時,它總是會觸發ng-repeat過濾器。

這是滯後於我的應用程序,因爲我在ng-repeat中使用了一大組。

這是爲什麼?

GIF: http://i.imgur.com/cStlXzy.gif

Plunker (打開控制檯,並看到自己)http://plnkr.co/edit/OxiutZ8t4IX1bOxiOTgo?p=preview

HTML:

<h3>Age list</h3> 
    <p>Selected: {{age.selected}}</p> 
    <ui-select ng-model="age.selected" ng-disabled="disabled" style="width: 300px;"> 
    <ui-select-match placeholder="Select a person">{{$select.selected}}</ui-select-match> 
    <ui-select-choices repeat="age in ageArray | filter: $select.search"> 
     <div ng-bind="age | highlight: $select.search"></div> 
    </ui-select-choices> 
    </ui-select> 

的JavaScript:

$scope.theFilter = function(item) { 
    console.log(item); 
    return item; 
    }; 

    $scope.ageArray = []; 
    $scope.$watch('people', function(item) { 
    for(var i = 0; i < item.length; i++) { 
     $scope.ageArray.push(item[i].age); 
    } 
    }); 

    $scope.people = [ 
    { name: 'Adam',  email: '[email protected]',  age: 10 }, 
    { name: 'Amalie', email: '[email protected]', age: 12 }, 
    { name: 'Wladimir', email: '[email protected]', age: 30 }, 
    { name: 'Samantha', email: '[email protected]', age: 31 }, 
    { name: 'Estefanía', email: 'estefaní[email protected]', age: 16 }, 
    { name: 'Natasha', email: '[email protected]', age: 54 }, 
    { name: 'Nicole', email: '[email protected]', age: 43 }, 
    { name: 'Adrian', email: '[email protected]', age: 21 } 
    ]; 

編輯:我甚至試圖過濾掉「數據集數組」中的屬性值,並在下拉菜單中使用它,但它不起作用。

編輯2:如果你認爲手錶是觸發這個,我刪除了手錶,這仍是一個問題:http://plnkr.co/edit/oD3Tt3vfjtOjADMnemW1?p=preview

編輯3:至今還沒有找到一個解決方案,這使我被困在chosen。我created an issue但沒有得到任何迴應。 如果您想修正這個問題,請提出問題。

回答

2

問題是過濾器在每個$digest(每ng-mouseenter,ng-click等)執行。對於一個龐大的數據集,這顯然可能會導致性能下降。 (請參閱此文章http://www.bennadel.com/blog/2489-how-often-do-filters-execute-in-angularjs.htm

請改爲在age.selected值上嘗試$watch,然後僅在該值實際發生更改時應用篩選器。

http://plnkr.co/edit/TIeKPAyrAQsGHwakqwEp?p=preview

HTML

<!-- filtered list "ageMatches" --> 
<ul ng-show="age.selected"> 
    <li ng-repeat="person in ageMatches">{{person.name}} - {{person.age}}</li> 
</ul> 

<!-- default list of all "people" --> 
<ul ng-hide="age.selected"> 
    <li ng-repeat="person in people">{{person.name}} - {{person.age}}</li> 
</ul> 

JS

// add age to scope 
$scope.age = {}; 

// add age match placeholder 
$scope.ageMatches = []; 

// watch age.selected for changes, apply filter 
$scope.$watch('age.selected', function(newVal, oldVal){ 
    if(newVal){ 
    $scope.ageMatches = $filter('filter')($scope.people, {age: newVal}); 
    } 
}); 
+1

謝謝你,但是這個過濾器,我使用非常複雜,包括在$不少NG-車型scope.filters。* - 我認爲爲每個人增加一塊手錶都很臃腫,而不是用ng-repeat。但問題是,ng-mouseenter是否必要?是否需要在懸停時觸發,而不是點擊?我個人認爲這是圖書館的一個缺陷。 – Gaui 2014-12-03 21:43:49

+1

同意,最糟糕的部分是,我認爲mouseenter的唯一目的是應用「主動」類...太糟糕了,最終導致性能下降#cssplease – SteamDev 2014-12-04 16:08:16

+2

可能會提示從lib代碼中的模板中刪除ng-mouseenter 。 – SteamDev 2014-12-04 16:28:36