Search code examples
angular-schema-form

Toggle readonly option for a field based on condition option


In reading the documentation for condition option it only supports hide/show fields based on how the expression for condition evaluates. Looking to see how instead to make a field "read-only" when the condition is met as opposed to removing it from the view.


Solution

  • If your condition is a function with no side-effects (i.e. its output only depends on inputs), you can watch for changes in inputs and re-evaluate condition.

    Imagine you have a condition that something needs to display only if both first name and last name are filled in. Then, you can do something like this:

    <div ng-if='hasFirstNameAndLastName'>...</div>
    

    JavaScript:

    function checkIfHaveFirstNameAndLastName() { 
       $scope.hasFirstNameAndLastName = ($scope.firstName && $scope.lastName);
    }
    
    $scope.$watch('firstName', checkIfHaveFirstNameAndLastName);
    $scope.$watch('lastName', checkIfHaveFirstNameAndLastName);
    

    I was actually thinking about baking something like this into angular-schema-form because re-evaluation of evalExpr() becomes a problem once application grows in size.