André Luiz André Luiz - 3 months ago 10
AngularJS Question

AngularJS - changing property value dynamically

I'm working with an angularjs app and I would like to set one of it's properties dynamically.

This is a piece of my model:

$scope.data_step_3 = {
'previous_insurance':{
'label':'Has this type of insurance ever been:',
'help_text':'',
'value':'',
'required':true,
'regex':''
},
'previous_insurance_description':{
'label':'If so, please explain (not applicable in Missouri):',
'help_text':'',
'value':'',
'required': true,
'regex':''
}
}


And I would to set the
required
property of
previous_insurance_description
dynamically. It would the
true
when
previous_insurance.value == 'Non-reviewed'


How can I do that?

Thanks for any help

Answer

To achieve expected result, use below option

HTML:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="x in data_step_3">
 <input value="" ng-model="x.value" ng-keyup="check()">
    <input value="" ng-model="x.label"><br>

  </div>
<span>Required value - {{data_step_3.previous_insurance_description.required}}</span>
</div>



</body>
</html>

JS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.data_step_3 = {
        'previous_insurance':{
            'label':'Has this type of insurance ever been:',
            'help_text':'',
            'value':'',
            'required':true,
            'regex':''
        },
        'previous_insurance_description':{
            'label':'If so, please explain (not applicable in Missouri):',
            'help_text':'',
            'value':'',
            'required': true,
            'regex':''
        }
}

    $scope.check=function(){
     var prevInsurance_val= $scope.data_step_3.previous_insurance.value;
      console.log(prevInsurance_val)
     if(prevInsurance_val =="Non-reviewed"){
       $scope.data_step_3.previous_insurance_description.required = false;
      }
      else{
         $scope.data_step_3.previous_insurance_description.required = true;
      }
    }
    console.log()
});

Codepen- http://codepen.io/nagasai/pen/YWbxpA