curuba
curuba

Reputation: 577

AngularJS directive to force a number format to the model

I need an input field with a mask but I want the model to keep the masked value.

Phone number should be displayed and stored in db in this format: ## ## ## ## ##.

I am using this library: formatter.js on the Web App and I try to understand what is the best way to use it with Angular for the mobile app.

Here is what I have so far:

Directive:

.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>

I have added the script in index.html:

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

The console returns :

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">

Upvotes: 3

Views: 686

Answers (1)

bardzusny
bardzusny

Reputation: 3828

By default, AngularJS is not using jQuery, only its small subset called jqLite:

Without full jQuery you won't be able to use any jQuery plugins (like formatter.js).

Luckily, if you include jQuery in your index.html before AngularJS itself - Angular will automatically use it as angular.element (instead of jqLite). Then you'll be able to access full jQuery functionality - including possibility to use its plugins.

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>

More information: https://docs.angularjs.org/api/ng/function/angular.element .

Upvotes: 1

Related Questions