【问题标题】:Why does adding a parameter to DDO factory function break the app?为什么向 DDO 工厂函数添加参数会破坏应用程序?
【发布时间】:2014-10-28 11:19:27
【问题描述】:

我的印象是(正确地,我的谷歌搜索显示)Javascript 函数可以采用任意数量的参数,而不管预期是什么。

所以奇怪的是我的指令在这里起作用

...
module.directive('aye', function(){
            return {
                restrict: 'AE',
                replace: 'true',
                template: "<p> Hi </p>"
            };
    });
    </script>
</head>

<body ng-controller="myController">
    <div>
        {{ airportsArray() }}
    </div>
    <div aye></div>
</body>
</html>

这里没有

module.directive('aye', function(injectables){
            return {
                restrict: 'AE',
                replace: 'true',
                template: "<p> Hi </p>"
            };
    });
    </script>
</head>

<body ng-controller="myController">
    <div>
        {{ airportsArray() }}
    </div>
    <div aye></div>
</body>
</html>

我只是删除参数(我在Angular's very own documentation 中找到)injectables。为什么这会给我这样的错误

Error: [$injector:unpr] http://errors.angularjs.org/1.2.15/$injector/unpr?p0=injectablesProvider%20%3C-%20injectables%20%3C-%20ayeDirective

谁能解释一下?

【问题讨论】:

  • 在文档中,injectables 是指您的injectables,而不是字面意义上的injectables。例如,如果您在应用程序中定义了一个名为 injectables 的服务,您的代码就可以工作。有意义吗?
  • 没有像injectables这样的服务。文档只是强调我们可以在指令定义函数中传递依赖项。

标签: javascript angularjs parameters


【解决方案1】:

Angular 通过依赖注入传入这些值。并根据参数的名称确定要注入的内容(当您进行缩小时可能会更复杂)。在上面的示例中,您没有识别名为“injectables”的组件(服务/工厂/值/等),因此它向您显示的错误是它找不到“injectables”

//Create something that can be injected:
module.service('fooService', function($http){
  /* ... some functions here ... */
});

//Inject this defined piece into your directive:
module.directive('myDirective', function(fooService){
});

当 Angular 需要创建“myDirective”的实例时,它会看到它需要参数“fooService”,因此它将进入其依赖解析器以找到它,然后将其作为参数传递给您的指令。

【讨论】:

  • 你能举个例子说明injectables的良好定义吗?
  • "injectables" 只是 Angular 的依赖注入机制可以注入的参数的占位符。话虽如此,我会在我的回答中举一个例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多