溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Angular.js如何實現(xiàn)多個checkbox只能選擇一個

發(fā)布時間:2021-06-21 13:41:50 來源:億速云 閱讀:203 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)Angular.js如何實現(xiàn)多個checkbox只能選擇一個的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

首先來看看效果

Angular.js如何實現(xiàn)多個checkbox只能選擇一個
效果

實現(xiàn)這樣的效果,必須使用指令了,只有使用指令才能單獨控制每一個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);
   };
  }
  }
 })
})()

這里簡單說一下,實現(xiàn)的主要思想就是,通過指令單獨生成scope,每一個指令都是一個單獨的scope,這樣每個ng-modal都獨立出來了,然后通過繼承一個總的指令來實現(xiàn)控制。

感謝各位的閱讀!關(guān)于“Angular.js如何實現(xiàn)多個checkbox只能選擇一個”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI