angularJS 報錯: [ngModel:numfmt] http://errors.angularjs.org/1.4.1/ngModel/numfmt?p0=333


<!doctype html>
<html ng-app="a10086">
<head>
    <meta charset="utf-8">
    <script src="angular.min.js"></script>
</head>
<body>

<pre>
stringToNumber2 指令中這么寫沒問題,
但是html中調用也這么寫,html解析會自動將標簽和標簽屬性專為小寫,即stringToNumber2變成了stringtonumber2,
導致最終:Error: ngModel:numfmt Model is not of type `number`。。產生的原因:不是你指令內寫錯了,而是指令(駝峰書寫)與html中調用的指令名稱(小寫)不相同
若html中調用指令改成:string-to-number2就可以了。。ng好變態。
</pre>
<div ng-controller="kkc">
 <input type="date"/>
 正確的<input type="number" string-to-number ng-model="cc.a"/> {{ cc.a }}
 錯誤的:<input type="number" stringToNumber2 ng-model="cc.b"/> {{ cc.b }}

</div>

</body>
</html>
<script>

angular.module('a10086',[])
.controller('kkc',function($scope){
    $scope.cc={
        a:'222',b:'333'
    }//雖然這里后台給出的a和b是字符串,但是指令會專為數字。
}).directive('stringToNumber', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(value) {
                return '' + value;
            });
            ngModel.$formatters.push(function(value) {
                return parseInt(value);
            });
        }
    };
}).directive('stringToNumber2', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(value) {
                return '' + value;
            });
            ngModel.$formatters.push(function(value) {
                return parseInt(value);
            });
        }
    };
});
</script>

 AngularJS v1.4.1

input type="number":原因是在ipad上需要調用數字鍵盤,所以需要用這個,若type="text"則是不會報錯了;根據提示信息將數據
$scope.cc={
        a:'222',b:'333'
    }改成cc.a=222,cc.b=333方可不報錯,但因為該數據是從后台過來的,所以需要進行處理,故使用指令解決。。
但是依然報錯,后來找到原因是指令大小寫的問題:stringToNumber2,而html中寫為stringToNumber2,看似一樣其實不一樣,因為瀏覽器在解析頁面標簽屬性時會將其變成小寫stringtonumber2,故“333”就沒有解析成功,看指令:stringToNumber,在html中調用指令使用2中方式:1為string-to-number,2指令直接小寫得了。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM