我已经创建了一个用于执行简单计算器的应用程序.
该应用程序可以正常运行(demo),但是在这里,在控制器中的calculate方法中,我已经用JavaScript编写了一些算术计算.因此,为了使我的棱角代码整洁,我创建了另一个名为common.js的文件,并将其放在该算术计算中.我正在使用lodash.js.但是当我尝试调用方法_.calculateResult($scope.firstNumber,$scope.secondNumber,$scope.selectedOperator);我收到以下异常.
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>
解决方法:
为什么要运作?
当您使用lodash时,_符号通常绑定到lodash,因此您将使用以下代码在lodash库中调用方法:
_.calculateResult($scope.firstNumber, $scope.secondNumber, $scope.selectedOperator );
确实,错误消息确认_是破折号.
而且,您的common.js文件永远不会将calculateResult导出到匿名函数之外的代码可访问的位置.如果在匿名函数window.calculateResult = calculateResult的末尾添加此语句,则可以在window上导出它.
window.calculateResult($scope.firstNumber, $scope.secondNumber, $scope.selectedOperator );
这应该解决您的直接问题. (window.calculateResult(…)中的窗口实际上是可选的,因为没有它,JavaScript解释器仍然会从全局范围中寻找calculateResult,但我希望使其明确.)
我强烈建议您研究一个适当的模块化系统,以避免使用诸如calculateResult之类的函数污染全局范围.