radio
<label class="radio-inline">
<input type="radio" class="imei-radio" name="elecRadioOptions" value="IMEI" ng-model="selectItem"> IMEI
</label>
<label class="radio-inline">
<input type="radio" class="licence-radio" name="elecRadioOptions" value="车架号" ng-model="selectItem"> 车架号
</label>
默认选中某个值:
在html中:
在input框中添加ng-checked = "true" 以及 required
在js中动态添加:
$(' .imei-radio').attr("checked","checked");或 $(' .licence-radio').attr("checked","checked");
获得选中的值:
1 可以在选择后,通过事件触发来获得ng-model中的值(ng-model保持一致),例如
<button ng-click="getData()">获取所选数值</button>
$scope.getData = function(){
console.log(" 所选取的值:“,$scope.selectItem );
}
2 可以通过$watch来监听所选选项
$scope.$watch( "selectItem",function(newValue,oldValue) {
console.log(newValue);
})
输出的值是value中的值,angularjs会将value的值填入到ng-model中
checkbox
<input id="flag" type="checkbox" ng-model="select_all" ng-change="selectAll()" class="selectAll">全选
勾选全选后,会将true/false填入ng-model中(即监听select_all)
$scope.selectAll = function(){
console.log($scope.select_all); //勾选全选后,输出true/false
}
<tr ng-repeat="item in persons">
<td><input type="checkbox" ng-model="item.checked" ng-change="selectOne()"></td>
<td>persons.name</td>
<td>persons.phone</td>
</tr>
在循环添加每个选项的checkbox时,注意ng-model中的值item.checked与ng-repeat中item保持一致,因为item代表的是每一条列表项,在控制器中会循环这些列表项,为item.checked赋值true或false,实现全选或不选
$scope.list = []; //选择的列表项
$scope.selectAll = function(){
if($scope.select_all){
//全选
angular.forEach($scope.persons,function(i){
i.checked = true; //即ng-model中的值
$scope.list.push(i);
})
}else{
//全不选
angular.forEach($scope.persons,function(i){
i.checked = false;
$scope.list = [];
})
}
}
$scope.selectOne = function(){
$scope.list = [];
angular.forEach($scope.persons,function(i){
if(i.checked){
$scope.list.push(i);
}
})
if($scope.list.length === $scope.persons.length){
$scope.select_all = true;
}else{
$scope.select_all = false;
}
}
单选时,每次都先清空$scope.list,然后对列表项进行循环,将check为true放入到list中,如果list的长度和列表项的长度相等时,全选checkbox框勾选,不等,取消勾选
最后,获取所选择的列表项,和radio一样,要么事件触发,要么监听$scope.list
$scope.$watch("list",function(newValue,oldValue){
console.log(newValue);
})
select
1 数据在html中添加
<select ng-model="city">
<option value="shanghai" ng-selected="city=='shanghai'">上海</option>
<option value="beijing" ng-selected="city=='beijing'">北京</option>
<option value="nanjing" ng-selected="city=='nanjing'">南京</option>
<option value="taizhou" ng-selected="city=='taizhou'">泰州</option>
</select>
$scope.city= 'shanghai'; //初始化选择城市
//监听选择的值
$scope.$watch("city",function(newValue,oldValue){
console.log(newValue)
})
2 在js中添加数据
$scope.typeOptions = [
{name: '1',value: '50'},
{name: '2',value: '100'},
{name: '3',value: '150'},
{name: '4',value: '200'}
]
选择的值会填入ng-model中:
<select ng-model="selectedSite" ng-options="option.value as option.value for option in typeOptions"></select>
初始化选择的值:
$scope.selectedSite = '50';
监听ng-model中的值,即可以得到选择的值
$scope.$watch("selectedSite",function(newValue,oldValue){
console.log(newValue);
})