0

我正在使用AngularUI-Bootstrap實現typeahead。我需要根據來自數據庫的一些值顯示分組結果。這裏的結果AngularUI-Bootstrap Typeahead:按類型對標題進行分組

[{ 
    "id": 1, 
    "label": "type_1", 
    "titles": [{ 
     "id": 1, 
     "label": "title_1" 
    }, { 
     "id": 2, 
     "label": "title_2" 
    }, { 
     "id": 3, 
     "label": "title_3" 
    }] 
}, { 
    "id": 2, 
    "label": "type_2", 
    "titles": [{ 
     "id": 4, 
     "label": "title_4" 
    }, { 
     "id": 6, 
     "label": "title_6" 
    }] 
}, { 
    "id": 3, 
    "label": "type_3", 
    "titles": [{ 
     "id": 8, 
     "label": "title_8" 
    }, { 
     "id": 9, 
     "label": "title_9" 
    }] 
}] 
  • 的例子如何通過類型AngularUI,引導分組事先鍵入的內容標題
+0

的文檔已經展示瞭如何定義一個下拉菜單,自定義模板的例子。使用類似的東西,並使用兩個嵌套的ng-repeat循環你的類型,然後你的標題。 https://angular-ui.github.io/bootstrap/#/typeahead –

+0

你的plunk是空的 – svarog

+0

謝謝JB Nizet,但我怎麼能定義自定義模板按類型分組,並選擇只有標題沒有類型? –

回答

1

JB Nizet是正確的,你應該使用自定義模板(default)。看看

// view 
<script type="text/ng-template" id="typeahead-match.html"> 
    <div ng-if="match.model.isGroup">{{match.label}}</div> 
    <a ng-if="!match.model.isGroup" ng-bind-html="match.label | uibTypeaheadHighlight:query"> 
    &nbsp;&nbsp;{{match.label}} 
    </a> 
</script> 

<input 
    type="text" 
    ng-model="selected" 
    uib-typeahead="item as item.label for item in getItems($viewValue)" 
    class="form-control" 
    typeahead-template-url="typeahead-match.html"> 

// controller 
myApp.controller('MainController', ['$scope', function($scope) { 
    var data = [{ 
    "id": 1, 
    "label": "type_1", 
    "titles": [{ 
     "id": 1, 
     "label": "title_1" 
    }, { 
     "id": 2, 
     "label": "title_2" 
    }, { 
     "id": 3, 
     "label": "title_3" 
    }] 
    }, { 
    "id": 2, 
    "label": "type_2", 
    "titles": [{ 
     "id": 4, 
     "label": "title_4" 
    }, { 
     "id": 6, 
     "label": "title_6" 
    }] 
    }, { 
    "id": 3, 
    "label": "type_3", 
    "titles": [{ 
     "id": 8, 
     "label": "title_8" 
    }, { 
     "id": 9, 
     "label": "title_9" 
    }] 
    }]; 

    $scope.getItems = function(text) { 
    var result = []; 

    _.each(data, function(group) { 
     result.push({ 
     label: group.label, 
     isGroup: true 
     }); 

     _.each(group.titles, function(item) { 
     if(_.startsWith(item.label, text)) { 
      result.push(item); 
     } 
     }); 

     if(result && result[result.length-1].isGroup) { 
     result.pop(); 
     } 
    }); 

    return result; 
    }; 
}]); 

Example

+0

非常感謝@Gennady Grishkovtsov,它的工作原理 –