javascript - 如何在 ng-repeat 中设置 ng-model 的值?

标签 javascript angularjs

我有一个 ng-repeat,我把它放在一个 select 标签中。 我希望能够修改不同选择的选定值。 这是我所拥有的: HTML

<div ng-controller="Ctrl">
    <div ng-repeat="user in users">
        <select ng-model="nbModel" ng-options="numValue.Text for numValue in numValues" ng-change="chooseUser(nbModel, user.id)">
                        </select>
        &nbsp;&nbsp;{{user.name}}&nbsp;&nbsp;-&nbsp;{{user.age}} years
    </div>
</div>

js

function Ctrl($scope) {
    $scope.numValues = [ {Id : '0',Text : '0'}, {Id : '1',Text : '1'}, {Id : '2',Text : '2' }];    
    $scope.users = [];

    $scope.users.push(new User(1, 'Luke', 23));
    $scope.users.push(new User(2, 'Maria', 26));
    $scope.users.push(new User(3, 'Mike', 45));

    angular.forEach($scope.users, function(equip) {
        //TODO to set the default values for each select
    });

    $scope.chooseUser= function(value, name) {
        //some traitement        
        //TODO to set a wanted value        
    };
};

function User(id, name, age) {
    this.id=id;
    this.firstnamename = name;
    this.age = age;
}

我不知道如何手动设置选定的选项。 有帮助吗?

最佳答案

您已经完成了一半...您需要做的是将 ng-model 设置为您想要更改的用户。假设您想通过选择更改用户的年龄,它看起来像这样:

<div ng-controller="Ctrl">
    <div ng-repeat="user in users">
        <select ng-model="user.age" ng-options="numValue.Text for numValue in numValues"></select>
        &nbsp;&nbsp;{{user.name}}&nbsp;&nbsp;-&nbsp;{{user.age}} years
    </div>
</div>

关于javascript - 如何在 ng-repeat 中设置 ng-model 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008823/

相关文章:

c# - 如何通过 HtmlDocument.InvokeScript 将对象作为参数传递给 javascript

javascript - 在父窗口上刷新子窗口

javascript - Promise 决议传递的是 Promise 而不是值(value)

angularjs - 使用 AngularJs 处理 Play scala 发送的分块数据

javascript - Angular 拖放克隆图像无法与助手一起使用 : 'clone' & placeholder: 'keep'

javascript - 在 Context 消费者上使用 useContext() 时,React Context "Property ' 状态'不存在

javascript - fullcalendar.io 使用 PHP/MySQL 渲染事件?

javascript - 禁用内容安全策略

javascript - 如何禁用所有 ng-click 和 ng-submit 事件

javascript - 在生成的模板中使用 yeoman-generator 变量