<!DOCTYPEhtml>
<htmlng-app="app">
<head>
<metacharset="utf-8">
<title>kendoAutoComplete範例:強化版</title>
<linkhref="//cdn.kendostatic.com/2014.2.716/styles/kendo.common.min.css"rel="stylesheet"/>
<linkhref="//cdn.kendostatic.com/2014.2.716/styles/kendo.default.min.css"rel="stylesheet"/>
<style>
.hi {
color: red;
}
.hint {
clear: both;
}
.f-l {
float: left;
}
.f-r {
float: right;
}
.symbol {
width: 100px;
}
</style>
</head>
<bodyng-controller="ctrl as vm">
<div>
<inputclass="symbol"kendo-auto-complete="vm.KendoObject"
k-options="vm.Options"ng-model="vm.Symbol"/>
<spanng-bind="vm.Name"></span>
</div>
<scriptsrc="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="//cdn.kendostatic.com/2014.2.716/js/kendo.all.min.js"></script>
<script>
var rawData = [
{ s: '1435', c: '中福', e: 'C.F.C.Y.CORP.' },
{ s: '1437', c: '勤益', e: 'GTM' },
{ s: '1471', c: '首利', e: 'SL' },
//...省略...
{ s: '8078', c: '華寶', e: 'CCI' },
{ s: '8101', c: '華冠', e: 'Arima Comm.' },
{ s: '8105', c: '凌巨', e: 'GiantPlus' },
{ s: '8249', c: '菱光', e: 'CSI' },
{ s: '9912', c: '偉聯', e: 'AIC' }
];
var book = {};
$.each(rawData, function(i, item) {
book[item.s] = item;
});
function myCtrl($scope) {
var self = this;
self.Symbol = "";
self.Name = "";
function hiliteKeywd(str, keywd) {
return str.replace(keywd, "<span class='hi'>" + keywd + "</span>")
}
self.Options = {
dataTextField: 's',
filter: "contains",
template: function (item) {
return"<div class='hint'><span class='f-l'>" + item.match +
"</span><span class='f-r'>" + item.s + " " + item.c +
"</span></div>";
},
open: function() {
//設定指示區寬度
self.KendoObject.list.width(250);
},
change: function() {
var symbol = this.value();
if (!symbol)
self.Name = "";
else
//股票代號連動名稱
self.Name = book[symbol] ? book[symbol].c : "";
},
dataSource: {
serverFiltering: true,
transport: {
read: function (e) {
//密技:dataSource.transport可用JavaScript取代Server呼叫
var keywd = e.data.filter.filters[0].value;
//輸入數字時比對s、否則比對c或n
var isNum = !isNaN(keywd);
//設定比對筆數上限
var count = 0, maxCount = 10;
//共用比對函式
function check(item, prop) {
if (item[prop].indexOf(keywd) > -1) {
count++;
item.match = item[prop].replace(keywd,
"<span class='hi'>" + keywd + "</span>");
returntrue;
}
returnfalse;
}
var res = isNum ?
$.grep(rawData, function (item) {
if (count < maxCount && check(item, "s"))
returntrue;
else
returnfalse;
}) :
$.grep(rawData, function (item) {
if (count < maxCount &&
check(item, "c") || check(item, "e"))
returntrue;
else
returnfalse;
});
//將比對結果傳回
e.success(res);
}
}
}
};
}
angular.module("app", ["kendo.directives"])
.controller("ctrl", myCtrl);
</script>
</body>
</html>