Javascript - 在Typeahead中显示名称并获取ID

时间:2016-05-08 06:26:19

标签: javascript angularjs typeahead.js

我在html中使用Typeahead。我想显示区域名称并获取区域ID。但我都显示并获得区域ID。怎么解决呢?

MYFILE,JS:

.
.
.
var regions = response.data.result;
console.log(regions);

以下是Inspect元素中结果的屏幕截图: enter image description here

我想在typeahead中显示regionName并获取regionId。

            var regionValue = regions.map(function(result) {
                return result.regionId;
            });
        $scope.autocomplete = $('.the-basics .typeahead').typeahead({
                hint: false,
                highlight: false,
                minLength: 1,
                datumTokenizer:  true
            },{
                name: 'states',
                source: substringMatcher(regionValue),
                templates:{
                    empty:[
                        '<div class="empty-message"> No result...</div>'
                    ]
                }
            })


var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;
    // an array that will be populated with substring matches
    matches = [];
    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');
    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });
    cb(matches);
  };
};

其实我想显示regionName并获取regionId。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我明白你想要的是在下拉区域中显示名称,当你选择你获得id的项目时,如果是这样你可以做以下事情只显示regionName做这个

$scope.autocomplete = $('.the-basics .typeahead').typeahead({
            hint: false,
            highlight: false,
            minLength: 1,
            datumTokenizer:  true
        },{
            name: 'states',
            source: substringMatcher(regionValue),
            templates:{
                empty:[
                     '<div class="empty-message"> No result...</div>'
                ],
                suggestion: function(data) {    
                       return '<p> + data.regionName + '</p>';
                    }
            }
        })

并在选择项目时获取元素的ID

$('.the-basics .typeahead').bind('typeahead:selected', function(obj,datum, name) {
   //put here you code after selected item
   datum.regionId
})

查看docs typeahead