为什么 AngularJS 服务工厂返回未定义
Why AngularJS service factory is returning undefined
我有如下服务
services.js
var CalculatorService = angular.module('CalculatorService', [])
CalculatorService.service('Calculator', function () {
this.square = function (a) { return a*a};
});
CalculatorService.factory('StringManipulation', function () {
var r= function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
});
然后controller如下,
var myApp = angular.module('myApp', ['CalculatorService']);
{
myApp.controller('StringController', function ($scope, StringManipulation)
$scope.findReverse = function () {
$scope.reversename = StringManipulation.reverseString($scope.name);
}
});
并在 View 上使用如下控制器
<div ng-controller="StringController">
Enter Name:
<input ng-model="name">
<button class="btn btn-info" ng-click="findReverse()">Reverse
</button>
<div>{{reversename}}</div>
</div>
我确定缺少一些基本的东西。我收到
错误
错误:error:undef
未定义值
有帮助吗?
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
Automatic semicolon insertion 导致了问题。您必须在 return 语句所在的同一行添加左大括号。否则语句变为 return;
.
return {
reverseString: function reverseString(name)
{
return r(name);
}
}
Angular 期望来自工厂的 $get
方法的 return 值。由于自动插入分号,您的 StringManipulation
工厂正在 returning undefined
。
我有如下服务
services.js
var CalculatorService = angular.module('CalculatorService', [])
CalculatorService.service('Calculator', function () {
this.square = function (a) { return a*a};
});
CalculatorService.factory('StringManipulation', function () {
var r= function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
});
然后controller如下,
var myApp = angular.module('myApp', ['CalculatorService']);
{
myApp.controller('StringController', function ($scope, StringManipulation)
$scope.findReverse = function () {
$scope.reversename = StringManipulation.reverseString($scope.name);
}
});
并在 View 上使用如下控制器
<div ng-controller="StringController">
Enter Name:
<input ng-model="name">
<button class="btn btn-info" ng-click="findReverse()">Reverse
</button>
<div>{{reversename}}</div>
</div>
我确定缺少一些基本的东西。我收到
错误错误:error:undef 未定义值
有帮助吗?
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
Automatic semicolon insertion 导致了问题。您必须在 return 语句所在的同一行添加左大括号。否则语句变为 return;
.
return {
reverseString: function reverseString(name)
{
return r(name);
}
}
Angular 期望来自工厂的 $get
方法的 return 值。由于自动插入分号,您的 StringManipulation
工厂正在 returning undefined
。