我是 Angular 世界的新手。我刚刚用 angularJS 编写了我的第一个程序。但它没有按照我期望的方式工作。这是代码。
var sampleApp = angular.module('sampleApp', []);
sampleApp.controller('FinanceController', ['$scope',
function($scope) {
$scope.salary = 0;
$scope.invest = 0;
$scope.result = function() {
return $scope.salary * $scope.invest * 0.01;
}
$scope.result2 = $scope.salary * $scope.invest * 0.01;
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
</head>
<body ng-controller="FinanceController">
Salary
<input type="text" name="salary" ng-model="salary">
<br>Percentage to spend on gadgets
<input type="text" name="invest" ng-model="invest">
<br>
<span>Case1: Total Amount in Rs. {{result()}} </span>
<br/>
<span>Case2: Total Amount in Rs. {{result2}} </span>
</body>
</html>
我不明白为什么我的 case2 没有显示正确的结果?
最佳答案
如果您只想查看值,[而不是操作它],请将您的 html 更改为
<span>Case2: Total Amount in Rs. {{salary * invest * 0.01}} </span>
根据评论,作业只完成一次。赋值语句右边返回一个值,赋值给作用域变量,业务到此结束。
To add up, Angular Data binding automatically updates the immediate variable that is bound to an input element in the view, not the variables that is formed by some expression that is constructed using this immediate variable.
如果您真的想存储和操作该值,您应该按照另一个答案的建议使用 $watch ..
关于javascript - 双向数据绑定(bind)不适用于表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27643595/