watch changes on JSON object properties

2019-09-09 08:31发布

I'm trying to implement a directive for typing money values.

var myApp = angular.module('myApp', []);

var ctrl = function($scope) {
        $scope.amount = '0.00';

        $scope.values = {
                amount: 0.00
        };
};

myApp.directive('currency', function($filter) {
    return {
        restrict: "A",
        require: "ngModel",
        scope: {
            separator: "=",
            fractionSize: "=",
            ngModel: "="
        },
        link: function(scope, element, attrs) {

            if (typeof attrs.separator === 'undefined' || 
                    attrs.separator === 'point') {
                scope.separator = ".";
            } else {
                scope.separator = ",";
            };

            if (typeof attrs.fractionSize === 'undefined') {
                scope.fractionSize = "2";
            };

            scope[attrs.ngModel] = "0" + scope.separator;
            for(var i = 0; i < scope.fractionSize; i++) {
                scope[attrs.ngModel] += "0";
            };

            scope.$watch(attrs.ngModel, function(newValue, oldValue) {

                if (newValue === oldValue) {
                    return;
                };

                var pattern = /^\s*(\-|\+)?(\d*[\.,])$/;

                if (pattern.test(newValue)) {
                    scope[attrs.ngModel] += "00";
                    return;
                };

            }, true);
        }
    };
});

HTML template:

<div ng-app="myApp">
    <div ng-controller="ctrl">
        {{amount}}<br>
        <input type="text" style="text-align: right;" ng-model="amount" currency separator="point" fraction-size="2"></input>
    </div>
</div>

I want to bind the value in my input element to values.amount item in controller but the watch instruction of my directive doesn't work.

How do I leverage two-way-data-binding to watch JSON objects?

To understand problem more precise I've created a jsfiddle.

The task is the following: Add extra zeros to the input element if user put a point. I mean if the value in input element say "42" and user put there a point, so the value now is "42." two extra zeros have to be aded like this "42.00".

My problems:

  1. If I use ng-model="amount" the logic in input element works, but amount value of outer controller doesn't update.

  2. If I use ng-model="values.amount" for binding, neither amount of outer controller nor input element logic works.

I really have to use ng-model="values.amount" instruction, but it doesn't work and I don't know why. Any ideas?

0条回答
登录 后发表回答