gpt4 book ai didi

javascript - AngularJS:将算术运算符传递给 ng-value

转载 作者:行者123 更新时间:2023-12-01 02:43:14 24 4
gpt4 key购买 nike

我是 AngularJS 新手。

我从简单的计算器应用程序开始,它执行 + - */ 操作。

模块:myMdl.js

var ap = angular.module("myMdl", [])

Controller :myCtrl1.js

ap.controller("myCtrl1", function($scope) {
$scope.Number1 = "1";
$scope.Number2= "2";
});

查看:Calculator.html

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

<h1> Calculator Application </h1>

<div ng-app="myMdl" ng-controller="myCtrl1">
<br>
Select Operator:
<ul>
<input type="radio" ng-model="Mdloperator" name="operator" ng-value="+" checked/> + <br>
<input type="radio" ng-model="Mdloperator" name="operator" ng-value="-" /> - <br>
<input type="radio" ng-model="Mdloperator" name="operator" ng-value="*"/> * <br>
<input type="radio" ng-model="Mdloperator" name="operator" ng-value="/"/> / <br>
</ul>
Enter Value's:
<ul>
<input type="number" ng-model="Number1" value="{{Number1}}" /> <br>
<input type="number" ng-model="Number2" value="{{Number2}}" /> <br>
</ul>
Result: <br>
<ul>
<input type="number" ng-model="result" value="{{Number1 + Mdloperator + Number2}}" placeholder="Result"/>
</ul>
</div>

<script src="myMdl.js"></script>
<script src="myCtrl1.js"></script>

</body>
</html>

最佳答案

1) ngValue需要表达式,但简单的 + 符号不是有效的表达式,它会在控制台中给出错误,这就是为什么在填充 type="radio"< 时必须使用字符串的原因 元素。

2) 当你处理字符串时,你必须使用 $parse service将此字符串计算为结果。

3) 无需使用ngModelinput type="number" 元素上的 value="{{...}}" 一起使用。

请参阅此处的示例:

angular.module("myMdl", [])
.controller("myCtrl1", function($scope, $parse) {
var ctrl = this;

ctrl.Mdloperator = '/';
ctrl.Number1 = 1;
ctrl.Number2 = 2;

ctrl.getValue = function(val){
return angular.isString(val) ? $parse(val)($scope) : val;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>


<h1> Calculator Application </h1>

<div ng-app="myMdl" ng-controller="myCtrl1 as $ctrl">
<br>
Select Operator:
<ul>
<input ng-repeat-start="op in ['+', '-', '*', '/'] track by $index" type="radio" ng-model="$ctrl.Mdloperator" name="operator" ng-value="op" /> {{::op}} <br ng-repeat-end/>
</ul>
Enter Value's:
<ul>
<input type="number" ng-model="$ctrl.Number1" /> <br>
<input type="number" ng-model="$ctrl.Number2" /> <br>
</ul>
Result: <br>
<ul>
<input type="number" value="{{$ctrl.getValue($ctrl.Number1 + $ctrl.Mdloperator + $ctrl.Number2)}}" placeholder="Result"/>
</ul>
</div>

关于javascript - AngularJS:将算术运算符传递给 ng-value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47415505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com