Angular 1.6.5中ui-select无法显示值的问题求助
嘿,我帮你找出导致ui-select在Angular 1.6.5里不显示选项的几个核心问题了,咱们一步步拆解:
1. ui-select版本和Angular 1.6.5不兼容
你原来用的ui-select应该是适配Angular 1.2.x这类早期版本的,当你升级到1.6.5后,旧版ui-select内部的一些API调用、生命周期逻辑已经跟新版本Angular对不上了——这种兼容性问题经常会导致组件静默失效,看起来没报错但就是不干活。
2. 数组迭代逻辑写错了
你的people是数组,但你在ui-select-choices的repeat里用了(key, person) in people这种遍历对象的语法,还错误地用了person.value.name——数组里的每个元素本身就是{name, email, ...},根本没有value属性啊!这会导致过滤器直接把所有元素都过滤掉,自然看不到选项。
3. Angular过滤器的严格化处理
Angular 1.3+对filter过滤器的规则更严格了,旧版本可能会忽略“不存在的属性”(比如你写的value),但新版本会直接判定所有元素都不匹配,结果就是没选项可显示。
修正后的代码示例
第一步:先升级ui-select到兼容版本
得用支持Angular 1.6.x的ui-select版本,比如0.19.x系列,这个很关键,不然改了代码也白搭。
第二步:修正ui-select的模板代码
把demo.html里的ui-select部分改成这样:
<p>Selected: {{person.selectedSingleKey}}</p> <ui-select ng-model="person.selectedSingleKey" title="Choose a person"> <ui-select-match placeholder="Select a person in the list or search his name/age..."> {{$select.selected.name}} </ui-select-match> <ui-select-choices repeat="person in people | filter: $select.search"> <div ng-bind-html="person.name | highlight: $select.search"></div> </ui-select-choices> </ui-select>
要是你确实需要绑定选中项的索引(而不是整个对象),可以把repeat改成:
<ui-select-choices repeat="index as person in people | filter: $select.search">
这时候person.selectedSingleKey存的就是选中项在数组里的索引值。
第三步:同步angular-sanitize版本
记得把angular-sanitize的版本也改成1.6.5,和Angular主版本保持一致,避免额外的兼容性坑。
小提示
打开浏览器开发者工具的控制台看看,有时候Angular的错误会被组件捕获,控制台里可能藏着你没注意到的警告或错误信息,能帮你更快定位问题~
内容的提问来源于stack exchange,提问作者tinyCoder

