checkBox 持久化数据为 逗号分割
/**
* 功能说明:
* htCheckbox 指令用于收集checkbox数据。
* 在页面中使用
* 属性指令:ht-checkbox
* 对应的值为scope对应的数据data.users=“1,3”。
* 示例:
<div >
<input type="checkbox" ht-checkbox ng-model="data.users" value="1" />红
<input type="checkbox" ht-checkbox ng-model="data.users" value="2" />绿
<input type="checkbox" ht-checkbox ng-model="data.users" value="3" />蓝
<span>{{data.users}}</span>
</div>
*/
.directive('htCheckbox', [ function() {
return {
restrict : 'A',
require : "ngModel",
link : function(scope, element, attrs, ctrl) {
var checkValue = attrs.value; //modelValue转viewValue的过程
ctrl.$formatters.push(function(value) {
if (!value) return false; var valueArr = value.split(",");
if (valueArr.indexOf(checkValue) == -1) return false; return true;
}); //viewValue转modelValue的过程
ctrl.$parsers.push(function(value) {
var valueArr = [];
if(ctrl.$modelValue){
valueArr = ctrl.$modelValue.split(",");
}
var index = valueArr.indexOf(checkValue);
if (value) {
// 如果checked modelValue 不含当前value
if (index == -1) valueArr.push(checkValue);
} else {
if (index != -1) valueArr.splice(index, 1);
} return valueArr.join(",");
});
}
}
}])