2014-07-02 42 views
0

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> 

但是,当我添加$表法,简化模板,整个页面失败,出现以下:

  • 没有startingEstimate显示在里面的所有输入元件

  • 的{{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

JS控制台错误?你能提供一个jsfiddle吗? btw测试$范围$ watch($ scope.funding.startingEstimate,computeNeeded);' –

回答

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); 
+0

谢谢@Pete :-)这工作正常。我也跟踪了下面的答案(下面),它几乎是一样的。会投票赞成,但没有足够的声誉:-( –

0

谢谢@Pete!

我能够追查以及:-)

这几乎是一样的@Pete提供的,只有我结合实际功能的变种声明。

工作声明的代码将computeNeeded声明为var,$ 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>