从视图中看控制器内部的功能

function inside a controller from view

我是 angular js 的新手,这是一本书的示例。作者提到,在更改资金时,它将显示 10 的倍数的推荐,如您在代码中所见。但是我们编译这个程序时没有显示任何建议。可以帮助我了解 $scope.computeNeeded 的工作原理吗..

<html ng-app>
    <head>
        <title>this is title</title>
        <script src='angular.js' type="text/javascript"></script>
    </head>
<body>

<form ng-controller="StartUpController">
Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">
Recommendation: {{funding.needed}}
</form>
<script type="text/javascript">
function StartUpController($scope) {
    $scope.funding = { startingEstimate: 0 };
    $scope.computeNeeded = function() {
        $scope.needed = $scope.startingEstimate * 10;
    };
}
</script>

</body>

</html>

你犯了一个简单的错误:

$scope.computeNeeded = function() {
$scope.needed = $scope.funding.startingEstimate * 10;
};

{{funding.needed}}应该是

{{needed}}

您的视图正在显示 funding.needed(本质上是 $scope.funding.needed),但您的函数正在修改 $scope.needed 此外,您的输入绑定到 funding.startingEstimate,但您的函数正在访问 $scope.startingEstimate

您需要访问和修改正确的内容:

$scope.computeNeeded = function() {
    $scope.funding.needed = $scope.funding.startingEstimate * 10;
};

嘿 simi 正在为你工作 fiddle 请查看演示 here 这是我的 html 代码

<div ng-app>
 <form ng-controller="StartUpController">
 Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">
 Recommendation: {{funding.needed}}
 </form>
</div>

和javascript代码

function StartUpController($scope) {
    $scope.funding = { startingEstimate: 0 };
    $scope.computeNeeded = function() {
        $scope.funding.needed = $scope.funding.startingEstimate * 10;
    };
}