two-way binding in directive template with parser and formatter

1727 查看

http://stackoverflow.com/questions/17116418/issues-performing-two-way-binding-in-directive-template-with-parser-and-formatte

app.directive('ngPrice', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
            function parse(string) { //with the div in the template function is never called
                return parseInt(parseFloat(string) * 100);
            }

            function format(string) { //with the div in the template, string is always 'undefined' and the function is only called once
                return parseFloat(parseInt(string) / 100).toFixed(2);
            }
            ngModel.$parsers.push(parse);
            ngModel.$formatters.push(format);
        }
    };
});