ionic -- 单选框使用数据双向绑定(angularjs)问题
今天在项目用需要使用<input>标签的type=radio 的双向绑定功能,一开始ng-model绑定的变量在controller里一直无法实现绑定功能;源码如下:
在html里的代码:
- <label for="group1"><input type="radio" id="group1" class="group" name="group" value="1" ng-model="choice" ><span>公开</span></label><br>
- <label for="group2"><input type="radio" id="group2" class="group" name="group" value="2" ng-model="choice" ><span>好友可见</span></label>
controller里代码:
- // 初始化单选框的值
- $scope.choice = 1;
- // 点击事件,获取被选中的单选框的value值
- $scope.send = function(){
- console.log($scope.authority.choice); // 一直为初始化的值:1
- };
不管我怎么获取,都获取不到单选框的值,后台发现原来是我绑定值的时候出了问题:
正确代码
- <label for="group1"><input type="radio" id="group1" class="group" name="group" value="1" ng-model="authority.choice" ><span>公开</span></label><br>
- <label for="group2"><input type="radio" id="group2" class="group" name="group" value="2" ng-model="authority.choice" ><span>好友可见</span></label>
controller:
- // 初始化单选框的值,并放到一个对象里面
- $scope.authority= {"choice" :1};
- // 点击事件,获取被选中的单选框的value值
- $scope.send = function(){
- console.log($scope.authority.choice); // 一直为初始化的值:1
- };
** ng-model = 对象属性
$scope.authority = {"choice":1} 必须以对象形式初始化值;
希望对大家能有帮助,不要像我一样在这个坑里花费这么长时间。。。