Angular.js实现多个checkbox只能选择一个的方法示例
更新时间:2017年02月24日 11:47:18 作者:MakingChoice
这篇文章主要给大家介绍了利用Angular.js实现多个checkbox只能选择一个的方法,文中给出了详细的示例代码,相信对大家具有一定的参考价值,下面来一起看看吧。
首先来看看效果

效果
实现这样的效果,必须使用指令了,只有使用指令才能单独控制每一个scope。
示例代码如下:
<div class="form-group">
<label class="col-sm-2 control-label">请选择文章主题色彩</label>
<div class="col-sm-10" theme-group>
<label class="i-switch m-t-xs m-r">
<input type="checkbox" input-theme >
<i></i>
</label>
<label class="i-switch bg-info m-t-xs m-r">
<input type="checkbox" input-theme>
<i></i>
</label>
<label class="i-switch bg-primary m-t-xs m-r">
<input type="checkbox" input-theme >
<i></i>
</label>
<label class="i-switch bg-danger m-t-xs m-r">
<input type="checkbox" input-theme>
<i></i>
</label>
</div>
</div>
(function () {
angular
.module("shishuoproject")
.directive("themeGroup",function(){
return{
controller: function () {
var scopeArray=[];
this.addScope= function (scope) {
var self=this;
scopeArray.push(scope);
scope.$on("$destory",function(){
self.removeScope(scope);
})
};
this.closeScope= function (scope) {
//var l=scopeArray.length;
angular.forEach(scopeArray, function (value) {
if(value!=scope){
value.flag=false;
}
})
};
this.removeScope= function (scope) {
var index=scopeArray.indexOf(scope);
if(index!==-1){
scopeArray.splice(index,1);
}
};
this.getIndex= function (scope) {
var index=scopeArray.indexOf(scope);
return index;
}
}
}
})
.directive("inputTheme",function(){
return{
restrict:'EA',
require:"^?themeGroup",
template:'<input type="checkbox" ng-click="choseTheme()" ng-model="flag">',
replace:true,
scope:{},
link: function (scope,element,attr,themeCon) {
var colorArray=['#27c24c','#23b7e5','#7266ba',' #f05050'];
themeCon.addScope(scope);
scope.choseTheme= function () {
themeCon.closeScope(scope);
var index=themeCon.getIndex(scope);
var color=colorArray[index];
scope.$emit("getArticleThemeColor",{'color':color});
console.log(scope.flag);
};
}
}
})
})()
这里简单说一下,实现的主要思想就是,通过指令单独生成scope,每一个指令都是一个单独的scope,这样每个ng-modal都独立出来了,然后通过继承一个总的指令来实现控制。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用Angular.js能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
相关文章
Angular ng-repeat遍历渲染完页面后执行其他操作详细介绍
这篇文章主要介绍了Angular ng-repeat遍历渲染完页面后执行其他操作详细介绍的相关资料,需要的朋友可以参考下2016-12-12
Angular 2父子组件数据传递之@ViewChild获取子组件详解
这篇文章主要给大家介绍了关于Angular 2父子组件数据传递之@ViewChild获取子组件的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定参考学习价值,需要的朋友们下面来一起看看吧。2017-07-07


最新评论