这是我的对象数组,它绑定到下拉列表:
$scope.dropdownOptions = [{value: "0", name: 'No'}, {value: "1", name: 'Yes'}];
我希望通过以下函数在下拉列表中根据所选的“值”返回相应的“名称”。现在我已经硬编码了返回值。
$scope.getDropdownDisplayValue = function(_key){
if(_key == "1")
return "Yes";
else if(_key == "0")
return "No";
else
return "n/a";
};
问题是,如果我修改该数组中对象的Names属性,我将不得不改变上述函数的返回值。为避免这种情况,我想搜索对象数组并返回相应的值。例如:
$scope.getDropdownDisplayValue = function(_key){
if(_key == "1")
return <get object.name where object.value == _key from dropdownOptions array>
else if(_key == "0")
return <get object.name where object.value == _key from dropdownOptions array>
else
return "n/a";
};
我可以为此编写一个自定义函数,但想知道我是否可以使用AngularJS或JavaScript中已有的东西。提前谢谢。
答案 0 :(得分:1)
这是你想要的吗?
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
// Although this object has the same properties as the one in $scope.options,
// Angular considers them different because it compares based on reference
$scope.incorrectlySelected = { label: 'two', value: 2 };
// Here we are referencing the same object, so Angular inits the select box correctly
$scope.correctlySelected = $scope.options[1];
});
的index.html:
<select ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options">
</select>
以上是来自angularJS官方website
的示例答案 1 :(得分:1)
是的,您可以使用filterFilter
服务。
例如
app.controller('ExampleCtrl', ['$scope','filterFilter', function($scope, filterFilter)
{
$scope.dropdownOptions = [{value: "0", name: 'No'}, {value: "1", name: 'Yes'}];
$scope.getDropdownDisplayValue = function(_key) {
var objs = filterFilter($scope.dropdownOptions , {value: _key});
if( objs.lenght > 0) {
return objs[0].name;
} else {
return 'n/a';
}
};
}]);
希望得到这个帮助。