javascript - 双向数据绑定(bind)不适用于表达式

标签 javascript angularjs

我是 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/

相关文章:

Javascript 动词检测

javascript - 使用评估的变量值而不是实际类型

javascript - 我正在尝试用 html 中的按钮编写一个简单的文本框(供人们在其中键入 url)

javascript - 如何使用 NodeJs 请求 GET 模块发送 cookie?

javascript - Angular 错误 [$injector :modulerr] Failed to instantiate module myApp

javascript - Angular $scope 在 Angular Controller 中的函数之外没有值

AngularJS ng-repeat Math Pow

javascript - 将日期选择器添加到动态添加的 HTML div

javascript - 当 ng-if 添加/删除元素时收到通知

javascript - 在 AngularJS 中解析请求的 URL 的最佳方式