我在我的 Angular 应用程序中使用 ui-router。
下面的应用程序不是实际的应用程序,而是代表我的问题的最小的小应用程序。感谢任何形式的帮助。
我在这样声明路由时使用了 resolve。
下面是需要解析的函数
angular.module('routerApp').formItemModel = function(){
return {
test: function(){
return {name: 'Jenish'}
}
};
}
和这样的路由定义:
$stateProvider.state('home.list', {
url: '/list',
templateUrl: 'partial-home-list.html',
resolve: $injector.instantiate(angular.module("routerApp").formItemModel, {}),
controller: function($scope, test) {
$scope.dogs = ['Bernese', 'Husky', 'Goldendoodle'];
$scope.name = test.name;
}
})
如果我有这样的 html,解析器和应用程序将完美运行:(partial-home-list.html)
<ul>
<li ng-repeat="dog in dogs">{{ dog }}</li>
</ul>
name: {{name}}
但我处于需要将此名称移动到指令的情况,因此我创建了这样的测试指令。
(function () {
'use strict';
angular.module('routerApp').directive('test', function () {
var linker = function (scope, element) {
}
var controllerFunction = function ($scope, test) { //How to inject test here as it reports error **Unknown provider: testProvider <- test**
$scope.name = test.name;
}
return {
controller: controllerFunction,
templateUrl: 'test.html',
restrict: 'E',
link: linker
};
});
}())
更新 partial-home-list.html 如下所示
<ul>
<li ng-repeat="dog in dogs">{{ dog }}</li>
</ul>
name: {{name}}
<test></test>
Here对于上面的例子来说是笨拙的。
最佳答案
您不能在指令中注入(inject)在状态中解析的数据,因为指令可以在 ui-view
之外使用,因此注入(inject)将无效。你应该像这样从 Controller 传递数据来查看:
scope: {
data: '='
}
查看:
<test data="test"></test>
参见 plunker
关于javascript - 如何在指令 Controller 中注入(inject)依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460922/