[英]How to inject dependencies in directive controller
我在我的角度應用程序中使用ui-router。
下面的應用程序不是實際的應用程序,而是代表我的問題的最小型小型應用程序。 任何幫助表示贊賞。
我在聲明這樣的路線時使用了決心。
以下是需要解決的功能
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>
對於上面的示例, 這很麻煩。
您不能在指令中插入以狀態解析的數據,因為指令可以在ui-view
外部使用,因此插入將無效。 您應將數據從控制器傳遞到視圖,如下所示:
scope: {
data: '='
}
視圖:
<test data="test"></test>
見朋克
您也可以對問題使用transclude選項。 像這樣
從您的范圍中刪除控制器,然后添加
transclude:true
指令中的選項。
<div>
<div>
<b>This is directive content with </b>
</div>
<ng-transclude></ng-transclude>
</div>
然后你可以像這樣使用指令
<test>This is the name {{name}}</test>
因此,名稱將從外部范圍而不是指令范圍獲取。
見朋克
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.