如何设置select语句的值

How do I set the value for a select statement?

本文关键字:select 语句 设置 何设置      更新时间:2023-09-26

http://jsfiddle.net/WcJbu/

当我选择一个人时,我希望最喜欢的东西选择器显示他们当前的选择。

    <div ng-controller='MyController'>
        <select ng-model='data.selectedPerson' ng-options='person.name for person in data.people'></select>
        <span ...> likes </span>
        <select ... ng-model='data.favoriteThing' ng-options='thing.name for thing in data.things'></select>
    </div>

$scope.data.people = [{
    name: 'Tom',
    id: 1,
    favorite_thing_id: 1
}, {
    name: 'Jill',
    id: 2,
    favorite_thing_id: 3
}];
$scope.data.things = [{
    name: 'Snails',
    id: 1
}, {
    name: 'Puppies',
    id: 2
}, {
    name: 'Flowers',
    id: 3
}];

我需要设置一个服务并添加手表吗?或者有没有一种[好]的方法可以直接在select中使用favorite_thing_id?

将第二个选择更改为:

<select ng-show='data.selectedPerson' ng-model='data.selectedPerson.favorite_thing_id' 
        ng-options='thing.id as thing.name for thing in data.things'></select>

thing.id as添加到ng-options将允许您根据其id而不是引用来选择data.things条目。将ng-model更改为data.selectedPerson.favorite_thing_id将使角度自动更改为基于selectedPerson.favorite_thing_id的正确选项。

jsfiddle:http://jsfiddle.net/bmleite/4Qf63/

http://jsfiddle.net/4Qf63/2/做我想做的事,但这很不令人满意。

$scope.$watch(function() {
    return $scope.data.selectedPerson;
}, function(newValue) {
    if (newValue) {
        $scope.data.thing = $filter('filter')($scope.data.things, {id: newValue.favorite_thing_id})[0];
    }
})

我希望从select语句中看到所有这些都是可能的。也许我会写一个指令。关联={key:matchValue}这样我就可以做

<select ... ng-model='data.thing' ng-options='t.name for t in data.things' association='{id: "data.selectedPerson.favorite_thing_id"}'></select>