我有一个对象数组:
$scope.allCategories = [{'name': 'cat1', 'description: ... },
{'name': 'cat2', 'description: ... },
{...}];
我之前使用过:
<select ng-model="mycategory" ng-change="test()">
<option ng-repeat="category in allCategories">{{ category.name }}</option>
</select>
哪种方法很好,但它不是“Angular方式”。所以我把它改成了:
<select ng-model="mycategory" ng-change="test()" ng-options="category.name for category in allCategories track by category.name"></select>
构建这个正确的html:
<select ...>
<option value="cat1" label="cat1">cat1</option>
<option value="cat2" label="cat2">cat2</option>
...
</select>
但是在test()
:
// called whenever select changes
$scope.test = function() {
console.log($scope.mycategory);
}
$scope.mycategory
打印出对象{'name': 'cat1', 'description: ... }
而不是字符串值。使用ng-repeat
的先前版本会给我字符串值,所以这让我失望了。
有没有办法在$scope.mycategory = $scope.mycategory['name'];
内没有test()
的情况下自动获取字符串值?
答案 0 :(得分:1)
这是代码:
<select ng-model="correctlySelected"
ng-options="category.name as category.name for category in allCategories">
</select>
答案 1 :(得分:0)
要获得精确选择的值,请更改您的测试方法,如下所示:
$scope.test = function() {
console.log($scope.mycategory);}
将您的html部分更改为
<select ng-model="mycategory" ng-change="test()" ng-options="category.name for category in allCategories"></select>