Tricky approach of parsing an object with 2 properties to 2 separate models in AngularJS

时间:2015-06-25 19:09:09

标签: angularjs

I have this code <input ng-model="attribute.name" typeahead="property as property.name for property in MyObject | filter:{ paramName:$viewValue }"> MyObject is { name : 'A', desc : 'A description' } attribute.name need to stay as a simple string. However, with the code above, attribute.name becomes an object which I don't want. So I changed the code to <input ng-model="attribute.name" typeahead="property.name as property.name for property in MyObject | filter:{ paramName:$viewValue }"> Everything is working great until I also needed to render "desc" key. It doesn't have to be in ng-model but as long as I can render it, that would be nice. I don't need two way binding for "desc" because I want the data to be editable in free form. Now that I'm only returning property.name which is not an object anymore, how do I access "desc" key?

1 个答案:

答案 0 :(得分:1)

查看typeahead页面上的最后一个示例:https://angular-ui.github.io/bootstrap/#/typeahead

我需要:

1 - 更改表达式以使对象完整但仅选择所需的属性。另外,使用ngModel.$viewValue提供要过滤的字符串。所以:

<input ng-model="attribute.name"
    typeahead="property as property.name for property in MyObject | filter:{name: $viewValue}">

2 - 定义模板以显示结果。您需要在此模板中设置模式,遵循规则以正确显示结果。其中一个例子是:

<script type="text/ng-template" id="resultPattern.html">
    <div>
        <span ng-bind="match.name | typeaheadHighlight:query"></span><br>
        <small ng-bind="match.desc"></small>
    </div>
</script>

3 - 最终input标记为:

<input ng-model="attribute.name"
    typeahead="property as property.name for property in MyObject | filter:{name: $viewValue}" typeahead-template-url="resultPattern.html">

编辑1:

你是对的,我在第3步输入错误:

<input ng-model="attribute.name"
    typeahead="property.name as property for property in MyObject | filter:{name: $viewValue}" typeahead-template-url="resultPattern.html">

这是一个Plunkr:http://plnkr.co/edit/pcjV40KxkBFdyIM3L0M4?p=preview

编辑2:

我已经使用回调函数更新了Plunkr,用于处理后面的选择:http://plnkr.co/edit/pcjV40KxkBFdyIM3L0M4?p=preview

此外,还有ngModel的格式化程序,您可以使用该格式化程序选择在选择后显示的项目,并将整个信息设为ngModel