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)控制。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者使用Angular.js能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Angular ng-repeat遍歷渲染完頁面后執(zhí)行其他操作詳細介紹
這篇文章主要介紹了Angular ng-repeat遍歷渲染完頁面后執(zhí)行其他操作詳細介紹的相關資料,需要的朋友可以參考下2016-12-12
Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件詳解
這篇文章主要給大家介紹了關于Angular 2父子組件數(shù)據(jù)傳遞之@ViewChild獲取子組件的相關資料,文中通過示例代碼介紹的非常詳細,對大家具有一定參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07
詳解angularjs中如何實現(xiàn)控制器和指令之間交互
本篇文章主要介紹了詳解angularjs中如何實現(xiàn)控制器和指令之間交互,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
AngularJS監(jiān)聽ng-repeat渲染完成的兩種方法
這篇文章主要介紹了AngularJS監(jiān)聽ng-repeat渲染完成的兩種方法,結合實例形式分析了AngularJS基于自定義指令及廣播事件實現(xiàn)監(jiān)聽功能的相關操作技巧,需要的朋友可以參考下2018-01-01

