如何重新编译指令的内容

时间:2017-04-05 15:46:24

标签: angularjs angularjs-directive compilation

我想通过自定义指令向输入元素添加'ng-pattern'指令。我不想直接在模板中执行它,但它看起来元素永远不会重新编译。有任何想法吗?提前谢谢!

HTML:

<input type="text" ng-model="personal.testNumber_string" my-model="personal.testNumber" dot-to-comma/>

指令:

    function dotToCommaConverter($compile) {
    return {
        require: 'ngModel',
        restrict: 'A',
        scope: {
            myModel: '='
        },
        controllerAs: 'dot2Comma',

        controller: function($scope) {

            this.myModel = $scope.myModel;
        },

        compile: function(tElem, tAttrs) {

            return {
                pre: function(scope, iElem, iAttrs) {


                },
                post: function(scope, iElem, iAttrs, modelCtrl) {

                    iElem.attr('ng-pattern', '/^-?[0-9]+(?:\,[0-9]+)?$/');
                    $compile( iElem.contents() )(scope);

                    modelCtrl.$setViewValue(String(scope.dot2Comma.myModel).replace('.', ','));
                    modelCtrl.$render();


                    modelCtrl.$parsers.push(function(inputValue) {

                        var transformedInput = inputValue.replace(/[^0-9,.-]/g, '');
                        transformedInput = transformedInput.replace('.', ',');
                        transformedInput = transformedInput.replace(' ', '');

                        if (transformedInput !== inputValue) {

                            modelCtrl.$setViewValue(transformedInput);
                            modelCtrl.$render();
                        }

                        if (!isNaN(Number(transformedInput.replace(',', '.')))) {
                            scope.myModel = Number(transformedInput.replace(',', '.'));
                        } else {
                            scope.myModel = undefined;
                        }

                        return transformedInput;
                    });
                }
            };
        }
    };
}

1 个答案:

答案 0 :(得分:0)

您需要将原始元素替换为已编译的元素。例如:

//Take the modify the original and recompile 
var compiledElement = $compile('<div>Changed HTML for the Element</div>')(originalElement.scope());
originalElement.replaceWith(compiledElement);

http://api.jquery.com/replaceWith/