= array(); } $post['classname'] = 'post'; } function comment_format(&$post) { global $conf, $uid, $gid, $forumlist; if (empty($post)) return; $forum = $post['fid'] ? forum_read($post['fid']) : ''; $thread = well_thread_read_cache($post['tid']); if ($thread) { //$post['fid'] = $thread['fid']; $post['closed'] = $thread['closed']; $post['subject'] = $thread['subject']; $post['url'] = $thread['url']; } else { $post['closed'] = 0; $post['subject'] = lang('thread_not_exists'); $post['url'] = ''; } $post['create_date_fmt'] = humandate($post['create_date']); //$post['message'] = stripslashes(htmlspecialchars_decode($post['message'])); $user = user_read_cache($post['uid']); $post['username'] = array_value($user, 'username'); $post['user_avatar_url'] = array_value($user, 'avatar_url'); $post['user'] = $user ? user_safe_info($user) : user_guest(); isset($post['floor']) || $post['floor'] = 0; // 权限判断 $post['allowupdate'] = 2 == array_value($forum, 'comment', 0) && ($uid == $post['uid'] || forum_access_mod($post['fid'], $gid, 'allowupdate')); $post['allowdelete'] = group_access($gid, 'allowuserdelete') && $uid == $post['uid'] || forum_access_mod($post['fid'], $gid, 'allowdelete'); $post['user_url'] = url('user-' . $post['uid'] . ($post['uid'] ? '' : '-' . $post['pid'])); if ($post['files'] > 0) { list($attachlist, $imagelist, $filelist) = well_attach_find_by_pid($post['pid']); // 使用图床 评论使用图床,mysql会过多,写死链接到内容是减轻mysql的过多的方法 if (2 == $conf['attach_on']) { foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换成图床 $post['message'] = FALSE !== strpos($post['message'], $url) && $attach['image_url'] ? str_replace($url, $attach['image_url'], $post['message']) : $post['message']; } } $post['filelist'] = $filelist; } else { $post['filelist'] = array(); } $post['classname'] = 'post'; } function comment_format_message(&$val) { global $conf; if (empty($val)) return; // 使用云储存 if (1 == $conf['attach_on'] && 1 == $val['attach_on']) { $val['message'] = str_replace('="upload/', '="' . file_path($val['attach_on']), $val['message']); } elseif (2 == $conf['attach_on'] && 2 == $val['attach_on']) { // 使用图床 list($attachlist, $imagelist, $filelist) = well_attach_find_by_tid($val['tid']); foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换成图床 $val['message'] = FALSE !== strpos($val['message'], $url) && $attach['image_url'] ? str_replace($url, $attach['image_url'], $val['message']) : $val['message']; } } else { $val['message'] = str_replace('="upload/', '="' . file_path($val['attach_on']), $val['message']); } //$val['message'] = stripslashes(htmlspecialchars_decode($val['message'])); } // 把内容中使用了云储存的附件链接替换掉 function comment_message_replace_url($pid, $message) { global $conf; if (0 == $conf['attach_on']) { $message = FALSE !== strpos($message, '="../upload/') ? str_replace('="../upload/', '="upload/', $message) : $message; $message = FALSE !== strpos($message, '="/upload/') ? str_replace('="/upload/', '="upload/', $message) : $message; } elseif (1 == $conf['attach_on']) { // 使用云储存 $message = str_replace('="' . $conf['cloud_url'] . 'upload/', '="upload/', $message); } elseif (2 == $conf['attach_on']) { // 使用图床 评论使用图床,mysql会过多,写死链接到内容是减轻mysql的过多的方法 list($attachlist, $imagelist, $filelist) = well_attach_find_by_pid($pid); foreach ($imagelist as $key => $attach) { $url = $conf['upload_url'] . 'website_attach/' . $attach['filename']; // 替换回相对链接 $message = $attach['image_url'] && FALSE !== strpos($message, $attach['image_url']) ? str_replace($attach['image_url'], $url, $message) : $message; } } return $message; } function comment_filter($val) { unset($val['userip']); return $val; } function comment_highlight_keyword($str, $k) { $r = str_ireplace($k, '' . $k . '', $str); return $r; } // //
function comment_message_format(&$s) { if (xn_strlen($s) < 100) return; $s = preg_replace('#.*?
#is', '', $s); $s = str_ireplace(array('
', '
', '
', '

', '', '', '', '' . ''), "\r\n", $s); $s = str_ireplace(array(' '), " ", $s); $s = strip_tags($s); $s = preg_replace('#[\r\n]+#', "\n", $s); $s = xn_substr(trim($s), 0, 100); $s = str_replace("\n", '
', $s); } // 对内容进行引用 function comment_quote($quotepid) { $quotepost = comment_read($quotepid); if (empty($quotepost)) return ''; $uid = $quotepost['uid']; $s = $quotepost['message']; $s = comment_brief($s, 100); $userhref = url('user-' . $uid); $user = user_read_cache($uid); $r = '
' . $user['username'] . ' ' . $s . '
'; return $r; } // 获取内容的简介 0: html, 1: txt; 2: markdown; 3: ubb function comment_brief($s, $len = 100) { $s = strip_tags($s); $s = htmlspecialchars($s); $more = xn_strlen($s) > $len ? ' ... ' : ''; $s = xn_substr($s, 0, $len) . $more; return $s; } ?>javascript - Angular: how to fire ngChange when input type=&quot;number&quot; but not entered a number - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular: how to fire ngChange when input type=&quot;number&quot; but not entered a number - Stack Overflow

programmeradmin10浏览0评论

I'm building an angular directive, where I have two number inputs and both together represent an age range.

What I want to achieve is being able to use this directive the following way:

<input-age-range
    name="ageRange"
    ng-model="filterUpdateVM.ageRange">
</input-age-range>
<span ng-if="myCtrlVM.form.ageRange.$error.ageRange">
    Please, enter a valid age range.
</span>

and be able to show a custom error when the entered age range is not correct.

My directive html template looks this way:

<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Minimum age"
           name="ageMin"
           min="18"
           max="80"
           ng-change="checkAndValidateAgeRange()"
           ng-model="ageRange.ageMin"
           ng-model-options="{allowInvalid: true}">
</div>
<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Maximum age"
           name="ageMax"
           min="18"
           max="80"
           ng-change="checkAndValidateAgeRange()"
           ng-model="ageRange.ageMax"
           ng-model-options="{allowInvalid: true}">
</div>

Every time the user types anything in an input, I wish to check the if the entered range is correct:

  • Both ages should be numbers
  • Both ages should be between 18 and 80
  • ageMin <= ageMax

So far ng-model-options="{allowInvalid: true}" will let the ngChange function inside my directive to be triggered in case any of the ages entered is not between the desired age range (18-80) - this way I can do some checking and set an input error if there's any and show it.

My problem here is that if the age entered at first is not a number, ngChange is not called: it won't be able to do the error checking so there won't be any errors to be shown. How can I have my ngChange function called in this case, without changing my input type="number"?

EDIT: Jsfiddle added: /

I'm building an angular directive, where I have two number inputs and both together represent an age range.

What I want to achieve is being able to use this directive the following way:

<input-age-range
    name="ageRange"
    ng-model="filterUpdateVM.ageRange">
</input-age-range>
<span ng-if="myCtrlVM.form.ageRange.$error.ageRange">
    Please, enter a valid age range.
</span>

and be able to show a custom error when the entered age range is not correct.

My directive html template looks this way:

<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Minimum age"
           name="ageMin"
           min="18"
           max="80"
           ng-change="checkAndValidateAgeRange()"
           ng-model="ageRange.ageMin"
           ng-model-options="{allowInvalid: true}">
</div>
<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Maximum age"
           name="ageMax"
           min="18"
           max="80"
           ng-change="checkAndValidateAgeRange()"
           ng-model="ageRange.ageMax"
           ng-model-options="{allowInvalid: true}">
</div>

Every time the user types anything in an input, I wish to check the if the entered range is correct:

  • Both ages should be numbers
  • Both ages should be between 18 and 80
  • ageMin <= ageMax

So far ng-model-options="{allowInvalid: true}" will let the ngChange function inside my directive to be triggered in case any of the ages entered is not between the desired age range (18-80) - this way I can do some checking and set an input error if there's any and show it.

My problem here is that if the age entered at first is not a number, ngChange is not called: it won't be able to do the error checking so there won't be any errors to be shown. How can I have my ngChange function called in this case, without changing my input type="number"?

EDIT: Jsfiddle added: http://jsfiddle/afkf96qh/

Share Improve this question edited Feb 22, 2017 at 13:01 charliebrownie asked Feb 22, 2017 at 11:47 charliebrowniecharliebrownie 6,16711 gold badges39 silver badges56 bronze badges 16
  • 3 If type="number" then how someone can enter not a number? – Vilas Kumkar Commented Feb 22, 2017 at 11:54
  • @Kumkar i.e. : 'eeeee' ) – Petr Averyanov Commented Feb 22, 2017 at 11:55
  • By typing any character. – charliebrownie Commented Feb 22, 2017 at 11:55
  • 1 @PetrAveryanov then on ng-change we can check if value conains eeeee or not – Vilas Kumkar Commented Feb 22, 2017 at 11:58
  • @Kumkar if entered a minAge that is not a number, you get a form.ageMin.$error.number error but ngChange is not triggered. I want to check this error inside my directive to set the validity of ngModel and being able to capture errors when using my directive. – charliebrownie Commented Feb 22, 2017 at 11:59
 |  Show 11 more ments

3 Answers 3

Reset to default 3

Finally after a day of trying to figure out what was going on, I achieved the behavior I was looking for.

First of all, ng-model-options="{allowInvalid: true}" had nothing to do in solving my problem, so I removed that out of my input. My directive html template looks this way now:

<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Minimum age"
           name="ageMin"
           min="18"
           max="80"
           ng-model="ageRange.ageMin"
           ng-change="checkAndValidateAgeRange()">
</div>
<div class="col-md-3">
    <input type="number"
           class="form-control"
           placeholder="Maximum age"
           name="ageMax"
           min="18"
           max="80"
           ng-model="ageRange.ageMax"
           ng-change="checkAndValidateAgeRange()">
</div>

The problem that caused not triggering ng-change="checkAndValidateAgeRange()" was the way I was initializing the ageRange variable at the ngModel $render function:

angular
    .module('myModule')
    .directive('myDirective', myDirective);

function myDirective() {

    var directive = {
        templateUrl: 'myTemplate.html',
        restrict: 'E',
        require:  ['^form', 'ngModel'],
        link: linkFunc
    };

    return directive;

    /////////

    function linkFunc(scope, element, attrs, ctrls) {
        scope.form = ctrls[0];
        scope.ageRange = {};
        scope.checkAndValidateAgeRange = checkAndValidateAgeRange;

        var ngModel = ctrls[1];
        ngModel.$render = getAgeRange;

        function checkAndValidateAgeRange() {
            // fired when the model changes
        };

        // $render function
        function getAgeRange() {
            scope.ageRange.ageMin = ngModel.$viewValue.ageMin;
            scope.ageRange.ageMax = ngModel.$viewValue.ageMax;
        };
    };

};

In some cases, both of the ngModel object's properties passed to the directive - ageMin and ageMax - could be undefined.

And we all know what happens when we have an input with restrictions such as type="[whatever]", min="18" or max="80" and the data entered in that input does not follow those requirements: it is set to undefined in the model.

So, if the above properties were initially passed to the directive set to undefined and you entered a value in the <input type="number ...> that, for example, was not numeric... the binded model's value would still be undefined, so there wouldn't be any changes in the model making the ng-change not trigger.

What I finally did to solve this, was to initialize both ageRange.ageMin and ageRange.ageMax to null if they are passed as undefined, at my $render function:

ngModel.$render = getAgeRange;

// $render function
function getAgeRange() {
    scope.ageRange.ageMin = ngModel.$viewValue.ageMin || null;
    scope.ageRange.ageMax = ngModel.$viewValue.ageMax || null;
};

This way, when entering an invalid input the model's property value will change from null to undefined causing the ng-change to trigger.

checkout this fiddle

$scope.checkAndValidateAgeRange = function(name, model) {
    if (name === 'ageMin') {
        if (angular.isNumber(model)) {
            if (model < $scope.age.min) {
                $scope.minAgeMessage = 'You are under age';
            } else if (model > $scope.age.max) {
                $scope.minAgeMessage = 'You are too old';
            } else {
                $scope.minAgeMessage = '';
            }
        } else {
            $scope.minAgeMessage = 'Enter Only Numbers';
            $scope.ageRange.ageMin = null;
        }
    }

    if (name === 'ageMax') {
        if (angular.isNumber(model)) {
            if (model <= $scope.ageRange.ageMin) {
                $scope.maxAgeMessage = 'You are under age';
            } else if (model > $scope.age.max) {
                $scope.maxAgeMessage = 'You are too old';
            } else {
                $scope.maxAgeMessage = '';
            }
        } else {
            $scope.maxAgeMessage = 'Enter Only Numbers';
            $scope.ageRange.ageMax = null;
        }
    }
}

you can't use allowInvalid on type='number' as given here. You can set type='text' and then handle validation inside the ng-change handler if your intent if using type='number' is showing validation messages.

To set validity of form inside a controller refer to this link.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论