解释从$ http响应添加的动态Html的指令

时间:2017-01-21 09:59:34

标签: angularjs compiler-directives dynamic-html

定义指令以添加数字输入

    app.directive('numericCheck', function () {
    return {
        link: function (scope, element, attr) {
            element.on('keypress', function (event) {  
                event = (event) ? event : window.event;
                if(/Firefox/.test(window.navigator.userAgent) && event.keyCode!=0) {
                    return true;
                }
                var charCode = (event.which) ? event.which : event.keyCode;
                if (charCode > 31 && charCode != 46 && charCode != 47 && charCode != 45 && (charCode < 48 || charCode > 57) || (charCode==45 && (event.target.selectionStart!=0 || event.target.value.indexOf('-')>=0)) || (charCode==46 && event.target.value.indexOf('.')>=0) || (charCode==47 && (event.target.selectionStart==0 || event.target.value.indexOf('/')>=0))) {
                    return false;
                }
                return true;
            });  
        }

    };
});

以下字符串是添加到div的响应。

{"question":"Two identical charts have different parts shaded. Which one is greater - 0.02 or 0.04?<br><br><br><br><input type='text' id='b1' name='blank_1' class='num_blank' size='5' numeric-check> is the greater number."}

将响应添加到HTML数字检查后,指令不起作用,它允许我们输入所有字符而不是数字值。

1 个答案:

答案 0 :(得分:0)

你有没有试过像:

app.directive('numericCheck', function () {
return {
    link: function (scope, element, attr) {
        element.on('keypress', function (event) { 
scope.$apply(function(){ 
            event = (event) ? event : window.event;
            if(/Firefox/.test(window.navigator.userAgent) && event.keyCode!=0) {
                return true;
            }
            var charCode = (event.which) ? event.which : event.keyCode;
            if (charCode > 31 && charCode != 46 && charCode != 47 && charCode != 45 && (charCode < 48 || charCode > 57) || (charCode==45 && (event.target.selectionStart!=0 || event.target.value.indexOf('-')>=0)) || (charCode==46 && event.target.value.indexOf('.')>=0) || (charCode==47 && (event.target.selectionStart==0 || event.target.value.indexOf('/')>=0))) {
                return false;
            }
            return true;
});
        });  
    }

};