AngularJS - 动态更改属性值

时间:2016-08-22 20:17:28

标签: javascript angularjs

我正在使用angularjs应用程序,我想动态设置其中一个属性。

这是我模特的一部分:

    $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':''
        }
}

我想动态设置required previous_insurance_description属性。当true

时,它会previous_insurance.value == 'Non-reviewed'

我该怎么做?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

要达到预期效果,请使用以下选项

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