Answer the question
In order to leave comments, you need to log in
How to correctly assign a value to a model?
Colleagues, good afternoon. Please suggest a solution.
The task was given to implement an input that allows you to enter only integer values.
My code:
<script>
angular.module("App", [])
.controller("defaultCtrl", function ($scope) {})
.directive("checkNumber", function () {
return function (scope, element, attributes) {
const number = element[0].value;
const numberAfter = attributes.checkNumber
scope.$watch('inputValue', function (newValue, oldValue) {
const limitNumber = function (newValue) {
if (newValue / Math.floor(newValue) != 1 && newValue != undefined) {
let result = Number.parseInt(newValue)
scope.inputValue = result
}
}
limitNumber(newValue)
})
}
})
</script>
</head>
<body ng-controller='defaultCtrl'>
<input type='number' value="{{inputValue}}" ng-model="inputValue" check-Number='0'>
</body>
Answer the question
In order to leave comments, you need to log in
It's better to do it a little differently - instead of listening to scope changes, it's better to bind to the input event and start from there. Another advantage of binding specifically to an event is that you can undo the change before the render happens. In the case of observing the value in the scope, in any case, you will make 2 input renders: first, you will draw with an invalid character, and then replace the value with a valid one (in the example, an invalid value appears for a fraction of a second, and then disappears again).
About the timeout - this is one way to apply updates to the view part. In order for Angular to draw a new value, it needs to complete a digest cycle - that is, go through the values and compare them. $timeout is one of the safer ways to do this, as it starts the digest cycle after it's finished.
Here is an example of how this can be done.
In your example, the directive is not needed - you just make watch from the controller and change the value if necessary.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question