当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular.js实现多个checkbox只能选择一个的方法示例

Angular.js实现多个checkbox只能选择一个的方法示例

2018年05月01日  | 移动技术网IT编程  | 我要评论

首先来看看效果


效果

实现这样的效果,必须使用指令了,只有使用指令才能单独控制每一个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能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网