如何将默认的"选择"ng模型设置为对象?



我正在尝试用angular创建一个搜索引擎接口。用户在表单中选择一些参数,单击"搜索",然后使用$location.search() 在url中填充参数

用于构建表单的搜索接口参数:

params = {
    milestones: [ "a", "b", "c", "d", etc. ], 
    properties: [ 
        { "name": "name A", type: "text" }, 
        { "name": "name B", type: "checkbox" }, 
        { etc. }
    ]
}

控制器内部:

$scope.query = $location.search();  // get the parameters from the url  
$scope.search = function (query) {  // set the parameters to the url
    $location.search(query);    
};

以及表单的html

<select ng-model="query.milestone_name" ng-options="ms for ms in params.milestones">
    <option value="">-select milestone-</option>
</select>
<select ng-model="property" ng-options="prop.name for prop in params.properties" ng-change="query.property_name=property.name">
<!-- if the object 'property' was passed in the url, it would look like this `%5Bobject%20Object%5D`, so its 'name' parameter is converted to a string -->
    <option value="">-select property-</option>
</select>
<span ng-switch="property.type">
    <label ng-switch-when="text">{{query.property_name}}: <input type="text" ng-model="query.property_value"></label>
    <label ng-switch-when="checkbox">{{query.property_name}}: <input type="checkbox" ng-model="query.property_value"></label>
</span>
<button ng-click="search(query)">search</button>

页面中的其他地方是结果列表。

用户还可以访问一个带有如下url的搜索结果页面:

http://myapp.com/search?milestone_name=a&property_name=name%20A

几乎所有操作都很好:显示结果列表,在select组件中预先选择了具有正确值的"里程碑"参数,但没有选择"属性"参数,因为它不是字符串,而是对象。

如何将select组件的默认值(ng模型)设置为对象?

或者我应该怎么做的其他想法?

使用对象数组进行选择迭代时,ng-options指令需要有一个对象属性来匹配(并区分数组)

使用指令声明的track by部分,例如

<select ng-model="property" ng-options="prop.name for prop in params.properties track by prop.name" ng-change="query.property_name=property.name">
<!-- if the object 'property' was passed in the url, it would look like this `%5Bobject%20Object%5D`, so its 'name' parameter is converted to a string -->
    <option value="">-select property-</option>
</select>

您可以在ngOptions中使用这种形式的理解表达式:为数组中的值标记组。Html下拉列表将只显示所选对象的名称。模型将包含整个选定对象。您可以从控制器设置选定的对象。

  <select ng-model="property"
          ng-options="prop as prop.name for prop in params.properties">
  </select>

请查看此plnkr示例。

ng-options正在生成一些要与ng-model一起使用的选项。在您的语法(prop.name for prop in params.properties)中,您已经告诉它绑定到数组中找到的对象(与它上的属性相反——这是您想要做的),并使用它的name属性作为要显示的值。因此,当您尝试将ng-model设置为不在ng-options数组中的对象时,什么都不会发生——我猜是因为它使用的是引用/浅相等,而不是深度相等。所以你应该做的是:

  • ng-options对象转换为字符串数组。

  • 使用涉及密钥的语法,例如:

prop.name as prop.name for prop in params.properties

http://jsfiddle.net/C5ENK/

如果这不符合您的需求,请告诉我原因,我会看看是否能提供进一步的帮助。

我找到了一种解决方案…

当选择属性时,它保存该对象的索引,然后当页面加载时,它将select的ng模型设置为该索引的值。它使用this:example来设置索引,这个example用于获取对象数组中该索引的值。

最新更新