我創建了一個應用程序在角度執行一個簡單的計算器。 該應用程序正常工作(demo),但在計算方法中,我在javascript中編寫了一些算術計算的控制器。所以爲了讓我的角碼清理乾淨,我創建了另一個名爲common.js的文件,我在那裏進行了算術計算。我正在使用lodash.js。但是當我試圖調用方法_.calculateResult($scope.firstNumber, $scope.secondNumber, $scope.selectedOperator);
我收到以下異常。Lodash Angular JS - 獲取TypeError:對象函數lodash(值)
TypeError: Object function lodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? ...<omitted>... } has no method 'calculateResult'
at Object.$scope.calculate (http://localhost:8080/RestSample/app/scripts/controllers.js:18:19)
任何人都可以請告訴我一些這方面的解決方案。
common.js
(function() {
var calculateResult = function(no1, no2, opp) {
var A = parseInt(no1);
var B = parseInt(no2);
var C = 0;
switch (opp) {
case '+':
C = A + B;
break;
case '-':
C = A - B;
break;
case '*':
C = A * B;
break;
case '/':
C = A/B;
break;
}
return C;
}
})();
controllers.js
var app = angular.module('app', []);
app.controller("appController", function($scope){
$scope.operators = ['+', '-', '*', '/'];
$scope.selectedOperator = $scope.operators[0];
$scope.calculate = function() {
$scope.result = _.calculateResult($scope.firstNumber, $scope.secondNumber, $scope.selectedOperator);
};
});
的index.html
<div ng-app="app">
<div ng-controller="appController">
<div class="offset4 span6 well">
<label>Enter a value :</label>
<input ng-model="firstNumber" type="text"> <br/><br>
<label>Another Value:</label>
<input ng-model="secondNumber" type="text"> <br/><br>
<label>Operator:</label>
<select ng-model="selectedOperator"
ng-options="operator for operator in operators"></select>
<br><br>
<button ng-click="calculate()">Calculate</button> <br><br>
Result: {{result}}
</div>
</div>
</div>
但當我把它叫做'window.calculateResult($ scope.firstNumber,$ scope.secondNumber,$ scope。selectedOperator);'我得到'TypeError:Object [object global]沒有方法'calculateResult'' –
我們不能通過其他方式調用它'_.calculateResult($ scope.firstNumber,$ scope.secondNumber, $ scope.selectedOperator);' –
您是否在'common.js'的匿名函數末尾添加了語句'window.calculateResult = calculateResult'?如果你*做了*並且你仍然收到錯誤,那麼問題可能是你的JavaScript被加載的順序。 – Louis