Siempre he usado la directiva ngRequired con una condición con undefined para indicar que si una variable es distinta a undefined que haga que el campo del formulario sea obligatorio.
<input type="text" name="variable" id="variable" ng-model="variable"
ng-disabled="variable === undefined" ng-required="variable !== undefined">
En mis 3 años con AngularJS (Angular 1) nunca he tenido problema con esta directiva, pero ahora me empieza a fallar y no consigo entender por qué. El problema que me da es que, por alguna razón, entra en bucle la directiva cambiando el valor de la "variable" entre el valor que le doy por defecto y undefined hasta que bloquea el navegador; sin embargo si le pongo distinto a null, por ejemplo, no tiene este comportamiento.
El error que me da la consola del navegador es:
Uncaught Error: [$rootScope: infdig] 10 $digest() iterations reached.
Aborting!Watchers fired in the last 5 iterations: [
[{
"msg": "fn: function () { var start = perf.now(); var ret = thatScope.$eval(watchExpression); var end = perf.now(); _digestEvents.push({ eventType: 'scope:watch', id: scopeId, watch: watchStr, time: end - start}); return ret;}",
"newVal": true,
"oldVal": false
}, {
"msg": "fn: function () {var start = perf.now();var ret = watchExpression.apply(this, arguments); var end = perf.now(); _digestEvents.push({eventType: 'scope:watch',id: scopeId,watch: watchStr, time: end - start});return ret;}",
"newVal": ""
}, {
"msg": "fn: function () { var start = perf.now();var ret = thatScope.$eval(watchExpression);var end = perf.now();_digestEvents.push({eventType: 'scope:watch',id: scopeId,watch: watchStr,time: end - start});return ret;}",
"newVal": true,
"oldVal": false
}, {
"msg": "fn: function () {var start = perf.now();var ret = thatScope.$eval(watchExpression);var end = perf.now();_digestEvents.push({ eventType: 'scope:watch',id: scopeId,watch: watchStr,time: end - start});return ret;}",
"newVal": true,
"oldVal": false
}],
[{
"msg": "fn: function () {var start = perf.now();var ret = thatScope.$eval(watchExpression);
Por lo que puedo ver es algún problema con el $watch de la directiva pero no entiendo que me cambie el valor de mi variable entre el valor que le doy yo y el undefined.
Si a alguien le ha pasado algo similar o sabe cómo arreglarlo se lo agradecería, no se me ocurre nada para solventar esto.
Muchas gracias.