Angular的新手,试图让书中的例子运行起来。示例是关于$ watch方法。以下代码工作正常:
<html ng-app>
<head>
<title>StartUp Calculator</title>
</head>
<body>
<form ng-controller='StartUpController'>
Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate" />
Recommendation: {{funding.needed}}
</form>
<script src="Scripts/angular.js"></script>
<script>
function StartUpController($scope) {
$scope.funding = { startingEstimate: 0 };
$scope.computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};
}
</script>
</body>
</html>
但是,当我添加$ watch方法并简化模板时,整个页面都会失败并显示以下内容:
输入元素
{{funding.needed}}变量在页面上显示为文字字符串
失败的代码是:
<html ng-app>
<head>
<title>StartUp Calculator</title>
</head>
<body>
<form ng-controller='StartUpController'>
Starting: <input ng-model="funding.startingEstimate" />
Recommendation: {{funding.needed}}
</form>
<script src="Scripts/angular.js"></script>
<script>
function StartUpController($scope) {
$scope.funding = { startingEstimate: 0 };
$scope.$watch('funding.startingEstimate', computeNeeded);
$scope.computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};
}
</script>
</body>
</html>
不知道导致这种情况发生的原因......需要帮助PLZ: - )
答案 0 :(得分:1)
只是代码中的一个错误。您在computeNeeded前面缺少$scope
。同样,将$scope.computeNeeded
放在$watch
上方,因为指针在当前$watch
之后才会被声明。
$scope.computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};
$scope.$watch('funding.startingEstimate', $scope.computeNeeded);
或者,我会这样做,这样你就可以把needed
放在任何你想要的地方。
function needed() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
}
$scope.computeNeeded = needed;
$scope.$watch('funding.startingEstimate', needed);
答案 1 :(得分:0)
谢谢@Pete!
我也可以追踪它: - )
它与@Pete提供的几乎相同,只是我将var声明与实际功能结合起来。
有效的代码将computeNeeded声明为var,并且$ watch在代码后面 (注意:我在原版之前和之后都有$ watch并且都没有用)
工作代码:
<html ng-app>
<head>
<title>StartUp Calculator</title>
</head>
<body>
<form ng-controller='StartUpController'>
Starting: <input ng-model="funding.startingEstimate" />
Recommendation: {{funding.needed}}
</form>
<script src="Scripts/angular.js"></script>
<script>
function StartUpController($scope) {
$scope.funding = { startingEstimate: 0 };
var computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};
$scope.$watch('funding.startingEstimate', computeNeeded);
}
</script>
</body>
</html>