ngModel:numfmt及ng-true-value、ng-false-value勾选错误

一 angularjs 报 ngModel:numfmt 错

Error: [ngModel:numfmt] http://errors.angularjs.org/1.5.5/ngModel/numfmt?p0=1
    at Error (native)
    at http://192.168.1.21:8020/AngularJS/js/angular.min.js:6:412
    at Array. (http://192.168.1.21:8020/AngularJS/js/angular.min.js:266:169)
    at http://192.168.1.21:8020/AngularJS/js/angular.min.js:285:117
    at n.$digest (http://192.168.1.21:8020/AngularJS/js/angular.min.js:142:168)
    at n.$apply (http://192.168.1.21:8020/AngularJS/js/angular.min.js:145:249)
    at http://192.168.1.21:8020/AngularJS/js/angular.min.js:21:117
    at Object.invoke (http://192.168.1.21:8020/AngularJS/js/angular.min.js:41:372)
    at c (http://192.168.1.21:8020/AngularJS/js/angular.min.js:21:38)
    at yc (http://192.168.1.21:8020/AngularJS/js/angular.min.js:21:332)"    /AngularJS/js/angular.min.js (117)

产生原因

ng-model 的变量类型与 input type 属性不符
<input type="number" ng-model="age" /> 
...
$scope.age = '1'; // 此处age为string类型
解决
$scope.age = 1; // 初始化变量为number
// 或者
$scope.str = '16';
$scope.age = parseInt($scope.str); // 强转为number

二 衍生bug ng-true-value或ng-false-value绑定的checkbox不能正常默认勾选



<input type="text" ng-model="age" />
<input type="checkbox" ng-model="age" ng-true-value="1" ng-false-value="2"  />
...
$scope.age = '1'; 
产生原因

ng-true-value=”1” 表示此处值为number类型 但是$scope.age及input输入的值为string类型

解决1

$scope.age以及input值改变为number类型 实际开发中可能需要使用 parseInt() 强转$scope.age

"number" ng-model="age" />
"checkbox" ng-model="age" ng-true-value="1" ng-false-value="2"  />
...
$scope.age = 1; 
解决2(常用)

ng-true-value ng-false-value的值加单引号 表示string类型 ng-true-value=“‘1’”
$scope.age以及input值改变为string类型 实际开发中可能需要 tostring() 强转 $scope.age

"text" ng-model="age" />
"checkbox" ng-model="age" ng-true-value="'1'" ng-false-value="'2'"  />
...
$scope.age = '1'; 

你可能感兴趣的:(---【AngularJs】)