如何将默认的'select'ng-model设置为对象?

Fra*_*ain 8 angularjs

我正在尝试使用angular进行搜索引擎界面.用户在表单中选择一些参数,单击"搜索",然后使用参数填充URL$location.search()

用于构建表单的搜索界面参数:

params = {
    milestones: [ "a", "b", "c", "d", etc. ], 
    properties: [ 
        { "name": "name A", type: "text" }, 
        { "name": "name B", type: "checkbox" }, 
        { etc. }
    ]
}
Run Code Online (Sandbox Code Playgroud)

在控制器内:

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

和表单的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>
Run Code Online (Sandbox Code Playgroud)

页面中的其他位置是结果列表.

用户还可以使用以下URL访问搜索结果页面:

http://myapp.com/search?milestone_name=a&property_name=name%20A
Run Code Online (Sandbox Code Playgroud)

几乎一切正常:显示结果列表,"里程碑"参数预先选择select组件中的正确值,但不是"属性"参数,因为它不是字符串,而是一个对象.

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

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

Zak*_*nry 27

当使用一个对象数组进行迭代时,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>
Run Code Online (Sandbox Code Playgroud)