简体   繁体   English

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

[英]AngularJS setting min and max value of the variable

I have some variable which I display just a text and have two buttons to increase or decrease it. 我有一些仅显示文本的变量,并且具有两个按钮来增加或减少它。 I need to set max and min value can go that way. 我需要设置最大值和最小值可以这样。 There are a lot of examples for input fields & range filters but I can't figure out how to adapt it to my case (JS/Angular noob here, sorry). 输入字段和范围过滤器有很多示例,但是我不知道如何使它适应我的情况(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>

And this HTML: 和这个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>

How to limit this for example to a -10 to +30 range? 如何将其限制在例如-10到+30范围内?

You can handle this with if else condition on ng-click 您可以使用ng-click上的if else条件来处理此问题

DEMO 演示

 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> 

You can disable your buttons with using ng-disabled . 您可以使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM