簡體   English   中英

AngularJS從選擇菜單中截斷ng-option值

[英]AngularJS truncate ng-option values from select menu

我有一個Angular Bootstrap select插件應用於我的選擇菜單,它將所選菜單項呈現為以下內容:

            <button data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">
                <div class="filter-option pull-left">Item with a very long name</div>&nbsp;<div class="caret"></div>
            </button> 

我正在嘗試開發一個函數,如果它大於指定的長度,它將截斷所選菜單項的名稱。

功能:

            $scope.truncate = function(){
                    var maxLength = 5;
                    $('button .filter-option').text(function(i, text) {
                        if (text.length > maxLength) {
                            return text.substr(0, maxLength) + '...';  
                        }
                    }); 
            }

在Angular模板中的原始選擇標記上調用的函數:

            <select
                class="nya-selectpicker"
                ng-model="items"
                ng-options="g.name for g in myItems"
                ng-change="truncate()">
                <option value="">Select</option>
            </select>

我的問題:這不是截斷我從菜單中選擇的項目;而是 它會截斷我模板中兩個相鄰選擇菜單的默認項。

如何更新此功能以截斷從菜單中選擇的項目?

因此,本質上您需要創建一個過濾器。 然后,您可以在ng-options應用此過濾器。

ng-options="(g.name | myFilter) for g in myItems"

myApp.filter('myFilter', function() {
  return function(val) {
    var maxLength = 5;
    if (val > maxLength) {
      return val.substr(0, maxLength) + '...';  
    } else {
      return val;
    }
  };
});

您可以改為對數組應用過濾器(我更喜歡上一個示例)

ng-options="g.name for g in myItems | myFilter"

myApp.filter('myFilter', function() {
  var maxLength = 5;
  return function(arr) {
    var returnArr = [];
    for(var i = 0; i < arr.length; i++) {
      (function() {
        var item = {};
        angular.copy(arr[i], item);
        if (item.name > maxLength) {
          item.name = item.name.substr(0, maxLength) + '...';
        }
        returnArr.push(item);  
      })();
    }
    return returnArr;
  };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM