AngularJS与Typeahead:基于选中值访问嵌套数组
解决AngularJS uib-typeahead动态加载嵌套数据的问题
嘿,我来帮你搞定这个typeahead动态加载的问题!你遇到的核心问题是几个小细节没对齐,导致品种和尺寸的输入框没法关联选中的商品,咱们一步步来修正:
先梳理现有代码里的问题
- 变量名不一致:商品输入框的
ng-model是selected.commodities,但后面品种输入框用的是selected.commodity,少了个s,这就导致拿不到选中的商品对象,自然没法加载嵌套数据。 getAttributeType函数未定义:你在前端模板里调用了这个函数,但控制器里根本没写它的逻辑,typeahead找不到数据源,就只能当成普通文本框用了。- typeahead表达式错误:尺寸输入框里的表达式
size.name for sizes in ...变量名混乱,而且参数传递也不对,应该直接指向选中商品的sizes数组。
修正后的完整代码
控制器代码(添加必要函数+确保数据逻辑)
angular.module('yourAppName', ['ui.bootstrap']) .controller('yourController', function($scope) { // 你的原始数据模型 $scope.languageModel = { brands: [{ id: 1, name: 'ALGS' }, { id: 2, name: 'BLVT' }], commodities: [ { id: 1, name: 'Apples', varieties: [{ id: 1, name: 'GS' }, { id: 2, name: 'GX' }], sizes: [{ id: 1, name: 'S' }, { id: 2, name: 'M' }], qualities: [{ id: 1, name: 'LQ' }, { id: 2, name: 'GQ' }] }, { id: 2, name: 'Oranges', varieties: [{ id: 1, name: 'OR' }, { id: 2, name: 'ZO' }], sizes: [{ id: 1, name: 'S' }, { id: 2, name: 'M' }], qualities: [{ id: 1, name: 'LQ' }, { id: 2, name: 'GQ' }] } ] }; // 初始化选中对象,避免undefined报错 $scope.selected = {}; // 定义你需要的getAttributeType函数(如果要复用逻辑的话) $scope.getAttributeType = function(attributeArray) { // 这里可以加一些过滤、排序逻辑,暂时直接返回数组 return attributeArray || []; }; // 你的setItem函数(如果需要的话) $scope.setItem = function(type) { console.log('Selected ' + type + ': ', $scope.selected[type]); }; });
前端模板代码(修正变量名+typeahead表达式)
<table> <tr> <th> <input id="brand" type="text" ng-model="selected.brand" ng-required="true" placeholder="Brand" uib-typeahead="brand.name for brand in languageModel.brands" class="form-control"> </th> <th> <input id="commodity" type="text" ng-model="selected.commodity" <!-- 这里把commodities改成commodity,和后面保持一致 --> ng-required="true" placeholder="Commodity" uib-typeahead="commodity.name for commodity in languageModel.commodities" <!-- 变量名统一成commodity --> class="form-control"> </th> <th> <input id="variety" type="text" ng-model="selected.variety" ng-required="true" placeholder="Variety" <!-- 直接用选中商品的varieties数组,或者调用getAttributeType --> uib-typeahead="variety.name for variety in getAttributeType(selected.commodity?.varieties)" class="form-control"> </th> <th> <input id="size" type="text" ng-model="selected.size" ng-required="true" placeholder="Size" <!-- 修正变量名和数据源,同时保留typeahead-on-select --> uib-typeahead="size.name for size in getAttributeType(selected.commodity?.sizes)" typeahead-on-select="setItem('size')" class="form-control"> </th> </tr> </table>
关键注意点
- 可选链操作符
?.:用selected.commodity?.varieties可以避免选中商品前出现undefined报错,AngularJS 1.7+支持这个语法,如果你的版本较低,可以换成selected.commodity && selected.commodity.varieties。 - 变量名统一:确保
ng-model的变量名前后一致,比如商品选中后存在selected.commodity里,后面的品种、尺寸都从这个对象里取数据。 - 函数定义:一定要在控制器里定义模板中用到的函数,否则AngularJS找不到对应的逻辑,会导致typeahead失效。
这样调整后,当你选中某个商品时,品种和尺寸的输入框就会自动加载对应商品的嵌套数组,实现动态关联啦!
内容的提问来源于stack exchange,提问作者Scrumptious
相关产品推荐
相关产品推荐

