I'm attempting to use a custom directive to make a conditional required statement. The first condition I've added is 'firstInArray' to make the element required if it's the first in array of choices (necessary for a UI where you need to pick at least one item, but you could pick indefinitely many):
.directive('variableRequired', [
()->
return {
require: 'ngModel',
link: (scope, el, attrs, ctrl)->
vars = attrs.variableRequired.split(',')
condition = vars[0]
if condition is 'firstInArray'
item = vars[1]
arr = vars[2]
if scope[item] == scope[arr][0]
$(el).removeAttr('variable-required')
$(el).attr('required', 'required')
}
])
When I add scope.$apply() within my directive, the app freezes up (seems like infinite recursion).
Is there a better way to approach this than a custom directive? If not, what's wrong with my directive?
You may be able to use the undocumented ng-required directive, instead of your own custom directive:
<li ng-repeat="itemObj in items">
<input type="text" ng-model="itemObj.text" ng-required="$first">
</li>