为什么AngularJS服务工厂返回undefined

时间:2015-02-17 10:21:20

标签: angularjs angularjs-service

我的服务如下

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);
   }
 }

 });

然后控制器如下,

   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>

我肯定会遗漏一些基本的东西。我收到了错误

错误:错误:undef 未定义的值

任何帮助?

1 个答案:

答案 0 :(得分:0)

return
 {
   reverseString: function reverseString(name)
   {
       return r(name);
   }
 }

Automatic semicolon insertion导致了这个问题。必须在与return语句相同的行上添加左括号。否则语句将变为return;

return {
       reverseString: function reverseString(name)
       {
           return r(name);
       }
  }

Angular期望从工厂的$get方法返回值。由于自动以分号插入,您的StringManipulation工厂正在返回undefined