AngularJS设置变量的最小值和最大值

时间:2018-07-27 14:11:36

标签: javascript angularjs

我有一些变量,我只显示一个文本,并有两个按钮来增加或减少它。我需要设置最大值和最小值可以这样。输入字段和范围过滤器有很多示例,但是我不知道如何使它适应我的情况(JS / Angular noob,抱歉)。

<script type="text/javascript">
    var airApp = angular.module('airApp', []);
    airApp.controller('dataShow', function($scope, $http, $filter) {
        $scope.init = function() {
            $scope.temp = +23.0; // Will be $http.request actually
        }
    });
</script>

这个HTML:

    <div class="container" align="center">
        <div class="page-header">
            <h1>Control</h1>
        </div>
        <div ng-app="airApp" ng-controller="dataShow" ng-init="init()" class="panel-body">
            <h1>
                {{temp > 0 ? '+' : ''}}{{temp | number : 1}}
                <button name="plus" ng-click="temp = temp + 0.5" class="btn btn-primary">+</button>
                <button name="minus" ng-click="temp = temp - 0.5" class="btn btn-primary">-</button>
            </h1>
        </div>
    </div>

例如,如何将其限制在-10到+30范围内?

2 个答案:

答案 0 :(得分:3)

您可以通过ng-click上的if else条件处理此问题

演示

var app = angular.module('testApp',[])
app.controller('dataShow', function($scope) {
    $scope.init = function() {
        $scope.temp = +23.0; 
     }
});
<!DOCTYPE html>
<html ng-app="testApp">

<head>
  <script data-require="angular.js@*" data-semver="4.0.0" 
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js">
  </script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="dataShow">
  <div class="container" align="center">
        <div class="page-header">
            <h1>Control</h1>
        </div>
        <div ng-app="airApp" ng-controller="dataShow" ng-init="init()" class="panel-body">
            <h1>
                {{temp > 0 ? '+' : ''}}{{temp | number : 1}}
                <button name="plus" ng-click=" (temp<30 ? temp = temp +0.5 : temp =30)"  class="btn btn-primary">+</button>
                <button name="minus" ng-click="(temp>-10 ? temp = temp- 0.5 : temp =-10)" class="btn btn-primary">-</button>
            </h1>
        </div>
    </div>
</body>

</html>

答案 1 :(得分:1)

您可以使用ng-disabled禁用按钮。

<button ng-disabled="(temp + 0.5) > 30" name="plus" ng-click="temp = temp + 0.5" class="btn btn-primary">+</button>
<button ng-disabled="(temp - 0.5) < -10" name="minus" ng-click="temp = temp - 0.5" class="btn btn-primary">-</button>