angularjs指令实现radioGroup

PHPABC angularjs 696 次浏览 没有评论

angularjs的指令系统其实也是很强大的东西,扩展了HTML的表现力。本文讲的是如何用angularjs指令实现radioGroup,自带的radio只能控制ngModel的两种状态: true/false

指令代码

module.directive('radio', [function() {     return {         transclude: true,         replace: true,         template: '<div class="ui ui-radio"><span class="radio-item"></span><span ng-transclude="" class="common-color"></span></div>',         require: 'ngModel',         link: function(scope, ele, attrs, ctrl) {             ctrl.$render = function() {                 if(ctrl.$viewValue == attrs.value) {                     //jqLite不支持siblings方法,如果此段代码无效,请使用zepto实现                     ele.parent().children().removeClass("active");                     ele.addClass("active");                 }             };             ele.bind("click", function() {                 ctrl.$setViewValue(attrs.value);                 ele.addClass("active");                 var childrens = ele[0].parentNode.children;                 for(var i = 0; i < childrens.length; i++) {                     if(childrens[i] != ele[0]) {                         angular.element(childrens[i]).removeClass("active");                     }                 }             });         }     }; }]);

LESS代码

.ui {   &-radio {     &.active {       .radio-item:after {         display: block;         width: 19px;         height: 19px;         content: ' ';         position: absolute;         border-radius: 50%;         left: (35px-19)/2;         top: (35px-19)/2;         background: #d14db7;       }     }     .radio-item {       width: 35px;       height: 35px;       border-radius: 50%;       position: relative;       background: white;       display: inline-block;       vertical-align: middle;       margin: 0;     }     span {       margin-left: 12px;     }   } }  

HTML代码

<div ng-init="answer='A'" class="options container-fluid wrapper">                 <div radio="" ng-model="answer" value="A">A. {{questions[index].option_a}}</div>                 <div radio="" ng-model="answer" value="B">B. {{questions[index].option_b}}</div>                 <div radio="" ng-model="answer" value="C">C. {{questions[index].option_c}}</div>                 <div ng-if="questions[index].option_d" radio="" ng-model="answer" value="D">D. {{questions[index].option_d}}</div>             </div> 

效果图

 

angularjs指令实现radioGroup

实际上会使用指令之后,逻辑不是难点。难在交互和样式

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Go