如何在AngularJS中(ng-repeat)获取选定的单选按钮数据

3

我需要通过单选按钮获取选定行的数据(id、name)。具体来说:

<tr data-ng-repeat=" list in listTypes">
    <td>{{list.TaskId}}</td>
    <td>{{list.Comments}}</td>
    <td>{{list.RecordDate}}</td>
    <td>{{list.StartDate}}</td>
    <td>{{list.DueDate}}</td>
    <td>{{list.AssignTo}}</td>
    <td>{{list.AssignBy}}</td>
    <td><label class="switch">
        <input type="radio" name="switch-radio1" checked="" value="0" ng-value="true" >
        <span></span>
    </label></td>
</tr>

当选择单选按钮时,我应该得到所选行的数据(taskIdcomments)。我应该使用哪个函数?(特别是JS部分) 感谢任何帮助。

Translated:

当选择单选按钮时,我应该得到所选行的数据(taskIdcomments)。我应该使用哪个函数?(特别是JS部分) 感谢任何帮助。

3个回答

2

您可以使用 ng-model 来处理复选框,方法如下:

<tr data-ng-repeat=" list in listTypes">
    <td>{{list.TaskId}}</td>
    <td>{{list.Comments}}</td>
    <td>{{list.RecordDate}}</td>
    <td>{{list.StartDate}}</td>
    <td>{{list.DueDate}}</td>
    <td>{{list.AssignTo}}</td>
    <td>{{list.AssignBy}}</td>
    <td>
         <label class="switch">
             <input type="radio" name="switch-radio1" ng-model="list.selected" ng-change="onTaskSelect(list)">
         </label>
    </td>
</tr>

现在你的控制器代码会像这样:
$scope.onTaskSelect = function(task) {
    // access your whole task object here.
    console.log(task.selected);    // will be true when you select it or else false
};

1

首先,您需要为单选按钮分配ng-model,并将ng-value更改为类似于list.TaskId的内容。

<input type="radio" name="switch-radio1" ng-model="selectedItem" checked="" value="0" ng-value="list.TaskId" >

现在你已经有了列表任务ID,可以使用Array.prototype.filter来查找listTypes中的数据。

Shashank Agrawal的答案更简洁。 - msohns
好的,那正是我需要的。顺便感谢你的回答。 - Semih Gokceoglu

1
我发现一种比其他方式更好的方法。当我们使用“ng-model”时,不需要name属性,并且由于使用了“$parent”,我认为可以访问单个模型来扮演name属性并绑定数据。因此,由于以下引用中的每个项都有一个作用域,我们必须有一个更高的级别来实现我们定义的单个模型。

ngRepeat指令会针对集合中的每个项实例化一次模板。 每个模板实例都有自己的作用域, 其中给定的循环变量设置为当前集合项,$index设置为项索引或键。 https://code.angularjs.org/1.7.5/docs/api/ng/directive/ngRepeat

$scope 属性:$parent 引用父作用域。 https://code.angularjs.org/1.7.5/docs/api/ng/type/$rootScope.Scope#$parent

在模板HTML中:

<table>
    <tr data-ng-repeat=" item in listTypes">
        <td>{{list.TaskId}}</td>
        <td>{{list.Comments}}</td>
        <td>{{list.RecordDate}}</td>
        <td>{{list.StartDate}}</td>
        <td>{{list.DueDate}}</td>
        <td>{{list.AssignTo}}</td>
        <td>{{list.AssignBy}}</td>
        <td>
             <label class="switch">
                 <input type="radio"  ng-model="$parent.rdoModel" ng-value="item" >
             </label>
        </td>
    </tr>
</table>
 <button type="button" ng-click="Ok(rdoModel)">OK</button>

在AngularJS控制器脚本中:
$scope.rdoModel={};
$scope.Ok = function(item){
var data = item ; // access to all data of list item
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接