rootscopeをディレクティブに渡される依存関係と考える方法がよくわからないため、この質問をしています
$rootScope からの情報を表示する必要があるディレクティブがあります ...
$rootScope をディレクティブに渡す必要があると思っていましたが、このようなディレクティブを書くとうまくいくようです。
.directive("myBar", function () {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
いつこれを行う必要がありますか?
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
ディレクティブのリンク関数で rootScope が必要な場合、どのように使用できますか? または、ディレクティブのコントローラーで使用する必要がありますか?
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
transclude: true,
replace: true,
link: function (scope, element, attrs, rootScope) {
rootScope.rsUser = { firstName: 'Joe' };
rootScope.rsUser = { welcome: 'Welcome' };
},
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
私の rootScope データは run 関数で定義されています
.run(function ($rootScope) {
$rootScope.rsLabels = {
welcome: 'Welcome'
};
$rootScope.rsUser = {
firstName: 'Joe'
};
});
ありがとうございました!