当我从控制器as test
调用它时,以下指令有效:
app.directive('codeblock', function() {
return {
scope: true, // Need to change this but not sure how
restrict: 'A',
replace: 'false',
template: '<div>{{ test.stateService.message }}</div>'
};
});
当我从控制器as abc
调用它时,以下指令有效:
app.directive('codeblock', function() {
return {
scope: true, // Need to change this but not sure how
restrict: 'A',
replace: 'false',
template: '<div>{{ abc.stateService.message }}</div>'
};
});
如何更改指令,以便传入:test.stateService
或abc.stateService
。我认为该指令需要如下所示:
app.directive('codeblock', function() {
return {
scope: true, // use a child scope that inherits from parent
restrict: 'A',
replace: 'false',
template: '<div>{{ stateService.message }}</div>'
};
});
但我不明白如何更改指令,所以我可以传递stateService以及我需要如何调用它。帮助将不胜感激。
答案 0 :(得分:1)
您可以将您想要的内容传递给指令
app.directive('codeblock', function() {
return {
scope: {
stateService:"="
}, // use a child scope that inherits from parent
restrict: 'A',
replace: 'false',
template: '<div>{{ stateService.message }}</div>'
};
});
在HTML中,
<div codeblock state-service="stateService"></div>
答案 1 :(得分:1)
如果它是service
,请将其传递,就像将服务传递给控制器一样。
app.directive('codeblock', ['stateService', function(stateService) {
return {
scope: true, // use a child scope that inherits from parent
restrict: 'A',
replace: 'false',
template: '<div>{{ stateService.message }}</div>',
link: function(scope, element, attrs) {
scope.stateService = stateService;
}
};
}]);
服务是单身,没有必要通过DOM传递它。