AngularJS UI Bootstrap 製作自動提示輸入效果- Typeahead
google 搜尋的時候,輸入一些字後就會有下拉建議的字,這個現在用 AngularJS 搭配 UI Bootstrap 做起來也很方便。
首先到 Angular UI Bootstrap 下載該下載的 css 和 js,或直接用 CDN。
- <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
- <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
基本用法:
- <input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control">
然後在 controller 裡放 json 格式的資料
- $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
方便的是還可以自己寫 template 基本用法也很簡單。
我準備這樣的 json
- $scope.belongData = [{
- "name": "Captain America",
- "group": "Marvel",
- "img": "captain_america.png"
- },
- {
- "name": "Daredevil",
- "group": "Marvel",
- "img": "daredevil.png"
- },
- {
- "name": "The Flash",
- "group": "DC COMIC",
- "img": "flash.png"
- },
- {
- "name": "Green Lantern",
- "group": "DC COMIC",
- "img": "greenlantern.png"
- },
- {
- "name": "Hulk",
- "group": "Marvel",
- "img": "hulk.png"
- },
- {
- "name": "Ironman",
- "group": "Marvel",
- "img": "ironman.png"
- },
- {
- "name": "Silver Surfer",
- "group": "Marvel",
- "img": "silversurfer.png"
- },
- {
- "name": "Spider Man",
- "group": "Marvel",
- "img": "spiderman.png"
- }
- ,
- {
- "name": "Thor",
- "group": "Marvel",
- "img": "thor.png"
- }
- ];
html 則是這樣
- <input type="text" ng-model="belongSelected" placeholder="Custom template" typeahead="belong as belong.name for belong in belongData | filter:{name:$viewValue}" typeahead-template-url="belongFilter.html" class="form-control">
從指定的 json 內找特定的資料,裡面有一個 typeahead-template-url 就是用來放自訂的樣式的,template 的寫法如下
- <script type="text/ng-template" id="belongFilter.html">
- <li class="list" >
- <div class="char_img">
- <img ng-src="{{match.model.img}}">
- </div>
- <div class="cha_name">{{match.model.name}}</div>
- <div class="cha_group">{{match.model.group}}</div>
- </li>
- </script>
把對應的值塞到想塞的地方,再調整樣式就可以了。
Demo
留言