I have a directive that prevents certain values from being entered into an input. For example this...
<input type="number" name="testValue" ng-model="testValue"
block="[0, 10, 17]" />
... will give a validation error if the user enters 0, 10, or 17.
This is working fine, but now I need to conditionally set the values being blocked depending on a variable in my controller, so I tried to use a ternary to set the value, like this...
<input type="number" name="testValue" ng-model="testValue"
block="blockValues ? [0, 10, 17] : []" />
However this is causing an Error: $rootScope:infdig Infinite $digest Loop, and I don't understand why. Could someone please explain this error to me and what I can do to fix it? Or any alternative would be appreciated as well. Thank you!
Here is a code snippet to demonstrate:
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.blockValues = true;
$scope.testValue = '';
});
myApp.directive('block', function() {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
scope: {
block: '='
},
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.allowedValues = function (value) {
return !scope.block || scope.block.indexOf(value) === -1;
};
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<!-- Errors -->
<input type="number" name="testValue" ng-model="testValue"
block="blockValues ? [0] : []" />
<!-- No Errors
<input type="number" name="testValue" ng-model="testValue"
block="false ? [0] : []" />
-->
<!-- No Errors
<input type="number" name="testValue" ng-model="testValue"
block="true ? [0] : []" />
-->
<!-- No Errors
<input type="number" name="testValue" ng-model="testValue"
block="[0]" />
-->
<!-- No Errors
<input type="number" name="testValue" ng-model="testValue"
ng-min="blockValues ? 1 : 0" />
-->
</form>
<div>{{myForm.testValue.$error}}</div>
</div>