OK! Looking at your demand, I took freedom and wrote a more individual directive.
Here is a fiddle for the same
Problem
The example from which you referenced and the changes made to this directive cause a problem.
- The variable names of the $ scope variable are incorrect in HTML / JS ($ scope.myNnumber1 = 1; $ scope.myNnumber2 = 1; in JS and in HTML it was ng-model = "myNumber1")
- You access
element ng-model and try to change it with a directive, which is bad practice, and also the main reason that the directive does not work. Since you do not change the value of ng-model , but, in turn, change the value of the HTML element, angular does not recognize. - Moreover, using the
$watch directive in a directive is not always preferable for performance.
Decision
app.directive('isNumber', function() { return { require: 'ngModel', restrict: 'A', link: function(scope, element, attr, ctrl) { function inputValue(val) { if (val) { var numeric = val.replace(/[^- 0-9]/g, ''); if (numeric !== val) { ctrl.$setViewValue(numeric ); ctrl.$render(); } return numeric; } return undefined; } ctrl.$parsers.push(inputValue); } }; });
When communication with the controller is required from the directive, we can pass the controller as 4 parameters in the link function. From this Ctrl parameter we can change / view objects from the control area.
Using some basic regex expression to find out what the input is, and set it in the object view of the control area object.
ctrl.$setViewValue(numeric);
More on $ setViewValue
source share