【问题标题】:Error: Unknown provider: aProvider <- a错误:未知提供者:aProvider <- a
【发布时间】:2012-10-07 06:52:30
【问题描述】:

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

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

Error: Unknown provider: aProvider <- a

我已经将它追溯到我的咖啡脚本文件,我在该文件中设置了 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 资产编译和缩小造成的吗? 有没有办法解决这个问题并仍然使用咖啡脚本和 Rails 资产?

【问题讨论】:

  • 我注意到,如果 $scope 被重命名,它会中断。我建议通过app.controller('TimesheetCtrl', ['$scope', function($scope) {...}]); 显式注入$scope(以与cofeescript 等效的方式)不过,可能还有其他这样的情况。

标签: ruby-on-rails ruby-on-rails-3 coffeescript angularjs


【解决方案1】:

AngularJS,当使用你现在使用的样式(称为 pretotyping)时,使用函数参数名称来进行依赖注入。所以是的,缩小确实完全打破了这一点。

不过,修复很简单。在您需要注入(使用'$xxx')变量的每种情况下,请执行以下操作:

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

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

docs 上还有更多(尽管不够清楚)信息。

【讨论】:

【解决方案2】:

如果你在某处遗漏了数组符号,要找到它,我们需要稍微修改一下角度代码,但它的解决方案非常快速。

更改是 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
【解决方案3】:

要缩小角度,您只需将声明更改为“数组”声明“模式”,例如:

发件人:

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

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 2014-03-08
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多