2014-07-02 60 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>