错误:未知提供者:aProvider <- a

7

我在一个带有资源的Ruby on Rails 3.2.8项目中使用AngularJS。

当我在我的开发机上加载使用AngularJS的表单时,没有问题。但是当我在生产服务器上加载相同的表单时,在Javascript控制台中会出现以下错误:

Error: Unknown provider: aProvider <- a

我已经追溯到我的coffeescript文件,那里我设置了AngularJS的使用方式,用于表单中:

$ (event) ->
  $("#timesheet_description").autocomplete({source: '/autocomplete/work_descs'})

  # Create AngularJS module
  app = angular.module 'timesheetApp', []

  # Create a AngularJS controller
  app.controller "TimesheetCtrl", ($scope) ->
    $scope.costed_amount = 0
                                                                                                # Bind my module to the global variables so I can use it.
  angular.bootstrap document, ["timesheetApp"]  

如果我把所有这些都注释掉,页面将会在没有错误和AngularJS能力的情况下加载。
问题是由于Rails资产编译和压缩吗? 有没有办法修复这个问题并仍然使用coffeescript和Rails资产?

1
我注意到如果$scope被重命名,它会出现错误。 我建议通过 app.controller('TimesheetCtrl', ['$scope', function($scope) {...}]); 显式注入 $scope(以与Cofeescript等效的方式)。虽然可能存在其他类似情况。 - Tosh
3个回答

20

AngularJS在使用目前所用的样式(称为pretotyping)时,使用函数参数名称进行依赖注入。因此,是的,缩小会完全破坏它。

不过,解决方法很简单。在每个需要注入(使用 '$xxx')变量的情况下,请执行以下操作:

app.controller "TimesheetCtrl", ['$scope', ($scope) ->
  $scope.costed_amount = 0
]

基本上,用一个数组替换所有函数定义。最后一个元素应该是函数定义本身,而前面的元素是您想要注入的对象的$names

关于此有更多信息(尽管不够清晰)在文档中。


这里有更多信息:http://docs.angularjs.org/tutorial/step_05 寻找“关于缩小的说明”。 - Lance Fisher
2
你可以使用非常好的ng-min模块,它会为你处理这个问题。在egghead.io上有非常好的解释:https://egghead.io/lessons/angularjs-ngmin - Mat
1
确保将此模式应用于特定指令的控制器! - anonymous

6

如果您在某个地方错过了数组符号,为了定位它,我们需要稍微修改一下 Angular 代码,但这是一个非常快速的解决方案。

更改如下:console.log("Array Notation is Missing",fn);(从函数起始行数第11行)

在未压缩的 angular.js 中找到 annotate 函数。

function annotate(fn) {
      var $inject,
          fnText,
          argDecl,
          last;

      if (typeof fn == 'function') {
        if (!($inject = fn.$inject)) {
          $inject = [];
          if (fn.length) {
console.log("Array Notation is Missing",fn);
fnText = fn.toString().replace(STRIP_COMMENTS, '');
        argDecl = fnText.match(FN_ARGS);
        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
          arg.replace(FN_ARG, function(all, underscore, name){
            $inject.push(name);
          });
        });
      }
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn');
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}

这是我找到丢失的数组语法的唯一方法。非常感谢!+1 - David L

0
要压缩Angular,你只需要将声明更改为“数组”声明“模式”,例如: 从:
var demoApp= angular.module('demoApp', []);
demoApp.controller(function demoCtrl($scope) {
} );

var demoApp= angular.module('demoApp', []);
demoApp.controller(["$scope",function demoCtrl($scope) {
}]);

如何声明工厂服务?
demoApp.factory('demoFactory', ['$q', '$http', function ($q, $http) {
    return {
          //some object
    };
}]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接