根据条件为属性赋值

时间:2018-05-07 05:36:20

标签: angularjs

我需要根据条件将输入字段的最大值设置为250或500.

我有一个ng-modal {{info.temp}},其中包含值1或0。

基于此,如果值为1,则可以在文本框中输入的最大数量为250,否则为500.

请告诉我如何在HTML格式的angularjs中编写此逻辑

2 个答案:

答案 0 :(得分:0)

运行此代码,您应该通过编辑更改temp并再次运行:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
  <form name="form">
    <label for="maxlength">Set a Info.Temp 0 or 1 : </label>
    <input type="number" ng-model="info.temp" id="maxlength" />
    <br>
    <label for="input">This input is restricted by the current Info.temp 1 = 250 and 0 = 500 char : </label>
    <input type="text" ng-model="name" id="input" name="input" ng-maxlength="info.temp ? 250 : 500" /><br>
    <hr>
    input valid? = <code>{{form.input.$valid}}</code><br>
    model = <code>{{name}}</code>
  </form>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "";
    $scope.info = { temp : 1};
});
</script>
</body>
</html>

答案 1 :(得分:0)

请添加一些代码示例。将条件设置为数字字段使用ng-max指令。

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <form name="form1">
      condition input: <input type="text" ng-init="condition=1" ng-model="condition" /> <br/> final input: <input name="result" type="number" ng-max="condition == '0' ? 250 : 500" ng-model="result" /> {{result }} <span ng-show="form1.result.$invalid"> Final input not valid</span>
    </form>
  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {

    });
  </script>

</body>

</html>
&#13;
&#13;
&#13;