指令来强制模型采用数字格式

AngularJS directive to force a number format to the model

本文关键字:数字 格式 模型 指令      更新时间:2023-09-26

我需要一个带遮罩的输入字段,但我希望模型保持遮罩值。

电话号码应以以下格式显示并存储在db中:## ## ## ## ## .

我在Web应用程序上使用这个库:formatter.js,我试图理解在移动应用程序中与Angular一起使用它的最佳方式。

到目前为止我写的是:

指令:

.directive('curubaTelephone', function () {
    return {
        restrict: 'AC',
        replace: false,
        link: function (scope, element) {
            element.formatter({
                'pattern': '{{99}} {{99}} {{99}} {{99}} {{99}}',
                'persistent': false
            });
        }
    }
})
HTML:

    <label class="item item-input item-stacked-label">
        <span class="input-label">Fixe</span>
        <input type="text" placeholder="fixe" ng-model="fonction.perso_fixe" class="curubaTelephone">
    </label>

我已经在index.html中添加了脚本:

<script src="lib/formatter/dist/jquery.formatter.min.js"></script>

控制台返回:

TypeError: element.formatter is not a function
    at link (http://localhost:8100/js/directives.js:48:25)
    at invokeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:16855:9)
    at nodeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:16365:11)
    at compositeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:15714:13)
    at compositeLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:15717:13)
    at publicLinkFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:15593:30)
    at $get.boundTranscludeFn (http://localhost:8100/lib/ionic/js/ionic.bundle.js:15732:16)
    at controllersBoundTransclude (http://localhost:8100/lib/ionic/js/ionic.bundle.js:16392:18)
    at ngRepeatAction (http://localhost:8100/lib/ionic/js/ionic.bundle.js:33138:15)
    at Object.$watchCollectionAction [as fn] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:22746:13) <input type="text" placeholder="fixe" ng-model="fonction.perso_fixe" class="curubaTelephone ng-pristine ng-untouched ng-valid">

默认情况下,AngularJS不使用jQuery,只使用它的小子集jqLite:

没有完整的jQuery,你将无法使用任何jQuery插件(如formatter.js)

幸运的是,如果你在index.html AngularJS之前包含jQuery, Angular会自动使用它作为angular.element(而不是jqLite)。然后你就可以访问完整的jQuery功能——包括使用它的插件的可能性。
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>

更多信息:https://docs.angularjs.org/api/ng/function/angular.element .