温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

AngularJS如何实现单选框及多选框的双向动态绑定

发布时间:2021-09-01 14:20:35 来源:亿速云 阅读:190 作者:小新 栏目:web开发

这篇文章给大家分享的是有关AngularJS如何实现单选框及多选框的双向动态绑定的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

AngularJS 在 <input type="text" /> 中实现双向动态绑定十分简单,如下所示:

<input type="text" ng-model="topic.title" />

只需要用ng-model 与 $scope 中的属性对应,即实现了type=”text” 的双向动态绑定。当 <input type="radio" /> 及 <input type="checkbox" /> 时情况略有不同:

1. <inputtype="radio" />

<input type="radio" name="person-action" value="go_home" ng-model="person.action" />回家 
<input type="radio" name="person-action" value="go_to_school" ng-model="person.action" />回学校

通过 value 属性指定选中状态下对应的值,并通过 ng-model 将单选框与 $scope 中的属性对应,便实现了 type=”radio” 时的双向动态绑定。

2. <input type="checkbox" />

<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="phone.play_sound" />铃声 
<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="phone.play_vibrate" />震动 
<input type="checkbox" ng-true-value="true" ng-false-value="false" ng-model="phone.play_lights" />呼吸灯

通过AngularJS 的内置指令 ng-true-value 和 ng-false-value ,指定多选框在选中和未选中状态下对应的值,再通过ng-model 将其与 $scope 中的属性对应,便实现了type=”checkbox” 的双向动态绑定。

但是理想跟现实总是相差太多,在实际操作过程中还是出现了问题。应该是ng-repeat中scope作用域的问题。

经过一番搜索、调试,自己终于将此问题解决了,效果图如下:

AngularJS如何实现单选框及多选框的双向动态绑定

核心源码

js

var str = ""; // 原来存放选中的项 
$scope.Selected = false; //默认未选中 
var choseArr=[]; // 定义数组用于存放前端显示 
$scope.check = function(z,x){ 
console.log("HUY:"); 
console.log(z); 
console.log("HUYU:"); 
console.log(x); 
if (x == false) { // 选中 
   str = str + z + ','; 
  } else { 
   str = str.replace(z + ',', ''); // 取消选中 
  } 
  choseArr = (str.substr(0,str.length-1)).split(','); 
 console.log("HY:"); 
 console.log(choseArr); 
 $scope.number_request = choseArr.length; // 前端显示所选数量 
 $scope.content_request = choseArr; // 前端显示所选请求ID 
};

Html

<tr ng-repeat="item in querydata"> 
<td ng-bind="$index+1">1</td> 
 <td><a ui-sref="#">{{item.postid}}</a></td> 
  <td>{{item.medname}}</td> 
  <td>{{item.medfact}}</td> 
  <td>{{item.medcnt}}</td>  
  <td>{{item.remark}}</td>   
  <td>{{item.tel}}</td>   
  <td>{{item.post_time}}</td> 
  <td><input id={{item.postid}} type="checkbox" ng-model="Selected" ng-click="check(item.postid,Selected)" /></td>   
</tr>

感谢各位的阅读!关于“AngularJS如何实现单选框及多选框的双向动态绑定”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI