Cleave.angular.js 2.01 KB
Newer Older
Myriam Guedey's avatar
Myriam Guedey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
angular.module('cleave.js', [])
    .directive('cleave', function () {
        return {
            restrict: 'A',
            require: 'ngModel',

            scope: {
                cleave: '&',
                onInit: '&?',
                onValueChange: '&?'
            },

            compile: function () {
                return {
                    pre: function ($scope, $element, attrs, ngModelCtrl) {
                        // eslint-disable-next-line
                        $scope.instance = new Cleave($element[0], $scope.cleave());

                        if ($scope.onInit) {
                            $scope.onInit()($scope.instance);
                        }

                        ngModelCtrl.$formatters.push(function (val) {
                            $scope.instance.setRawValue(val);

                            return $scope.instance.getFormattedValue();
                        });

                        ngModelCtrl.$parsers.push(function (newFormattedValue) {
                            if ($scope.onValueChange) {
                                $scope.onValueChange()(newFormattedValue);
                            }

                            return $scope.instance.getRawValue();
                        });

                        // Recreate cleave instance if any cleave options change
                        $scope.$watch(function() {
                            return $scope.cleave();
                            // eslint-disable-next-line
                        }, function (newOptions, oldOptions) {
                            $scope.instance.destroy();
                            // eslint-disable-next-line
                            $scope.instance = new Cleave($element[0], newOptions);
                        }, true);

                        $scope.$on('$destroy', function () {

                            $scope.instance.destroy();
                            $scope.instance = null;
                        });
                    }
                };
            }
        };
    });