Problem:
I am trying to use $scope.$watch
method over a ng-model used in a number input with strict attributes like, max
, min
, maxlength
and step
.
When the value inserted in the input exceeds any of those attributes, the ng-model retrieves undefined
.
So, eventually, what happens is: $scope.$watch
is triggered every time we change value in the input. Once the value is undefined, it will only be triggered again when the inserted value is again valid , in other words, following attribute rules (max, min, maxlength and step).
Eg
user input: -2,4 -> $scope.$watch
is triggered, and outputs, newValue
as undefined
.
user adds a new digit: -2,44 -> $scope.$watch
is not triggered anymore, this way.
main.js
$scope.$watch("user.input.base.sphere", function(newValue, oldValue) {
console.log(newValue);
}
**index.html
<input
ng-cloak
type="number"
ng-class="user.settings.input.sphere.class"
autocomplete="off"
required
name="sphere"
id="in-sphere"
title="Sphere"
step="{{user.filter.sphere.step}}"
min="{{user.filter.sphere.min}}"
max="{{user.filter.sphere.max}}"
maxlength="{{user.filter.sphere.maxlength}}"
placeholder="{{user.filter.sphere.placeholder}}"
ng-model="user.input.base.sphere"
select-on-click
sphere>
Question: How can I still let $scope.$watch
to be triggered even over a undefined ng-model
You can attach the following function to the ng-keyup
directive. This function will get a reference to your form control and read the value that the user has typed in even though the value in the model has not yet been updated.
$scope.changeHandler = function (a) {
var element = angular.element(document.querySelector('#in-sphere'))[0];
console.log(element.value);
}
Attach it to your form control with this: ng-keyup='changeHandler()'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.