在html里有这样几个复选框和一个按钮:
然后在js脚本里写了一个函数,让点击提交按钮时输出这些复选框的值:
$scope.songdan=function(){ var arr=new Array(); console.log($scope.tiantian); if ($scope.tiantian==true) arr.push("tiantian"); if ($scope.quanfeng==true) arr.push("quanfeng"); if ($scope.yousu==true) arr.push("yousu"); if ($scope.yuantong==true) arr.push("yuantong"); if ($scope.zhongtong==true) arr.push("zhongtong"); if ($scope.yunda==true) arr.push("yunda"); if ($scope.huitong==true) arr.push("huitong"); console.log(arr); };
然而输出的$scope.tiantian
是undefined
,输出的arr
是[]
,请问是为什么啊
我记得遇到过,请教了前辈,貌似是个坑,前辈给做了一个指令,相当于对这个坑打了个布丁,标签就正常写,指令放在全局模块里就可以了
angular.module('core').directive('input', function () { return { priority: 1000, restrict: 'E', require: '?ngModel', link: function (scope, element, attr, ctrl) { if (attr.type === 'checkbox' && ctrl && attr.value) { ctrl.$parsers = []; ctrl.$parsers.push(parserFn); ctrl.$formatters = []; ctrl.$formatters.push(formatterFn); } function formatterFn(val) { if (angular.isString(val)) { return val === attr.value; } else if (angular.isArray(val)) { for (var i = 0; i < val.length; i++) { if (val[i] === attr.value) { return true; } } return false; } } function parserFn(val) { if (angular.isString(ctrl.$modelValue)) { if (ctrl.$modelValue === '') { return val ? attr.value : ''; } return val ? (attr.value !== ctrl.$modelValue ? [ctrl.$modelValue, attr.value] : ctrl.$modelValue) : (attr.value === ctrl.$modelValue ? '' : ctrl.$modelValue); } else if (angular.isArray(ctrl.$modelValue)) { var $$modelValue = ctrl.$modelValue.slice(0); if ($$modelValue.length === 0) { if (val) { $$modelValue.push(attr.value); } return $$modelValue; } var existsBool = false; for (var i = 0; i < $$modelValue.length; i++) { if ($$modelValue[i] === attr.value) { if (val) { existsBool = true; break; } else { $$modelValue.splice(i, 1); } } } if (val && !existsBool) { $$modelValue.push(attr.value); } return $$modelValue; } return val; } } }; });
是点了核选框也不行吗?如果没核选框没有选,那么对应的变量就是undefined,因为变量没有做过初始化。可以在controller里做,也可以用ng-init="tiantian=false"做。
绑定复选不应该是ng-true-value ng-false-value么!?
绑定复选不应该是ng-true-value ng-false-value么!?
你的ng-modal="formdata.tiantian" 那么你应该$scope.formdata.tiantian这样写把
可以看看这个 对比你的代码 有哪些地方不对 然后模仿写出checkbox 链接