在AngularJS中,可以使用ng-options
指令来将数组绑定到ui-select
,但是如果需要将字符串绑定到ui-select
,需要进行一些额外的处理。
以下是一个示例解决方案:
HTML代码:
{{$select.selected}}
{{item}}
AngularJS控制器代码:
app.controller('MyController', function($scope) {
// 字符串数组
var itemString = "Apple, Banana, Orange, Mango";
// 将字符串分割为数组
$scope.items = itemString.split(', ');
// 选中项
$scope.selectedItem = "";
// 将选中项的字符串值设置到ng-model
$scope.$watch('selectedItem', function(newVal){
$scope.selectedItem = newVal;
});
});
在上述示例中,我们首先将字符串"Apple, Banana, Orange, Mango"
分割为数组,并将其绑定到ui-select
的repeat
属性上。然后,我们通过监视选中项的变化,并将其值设置为字符串值,以确保ng-model
中的值始终为字符串。
这样,ui-select
就可以接受字符串而不是数组作为选项了。