Angularjs 如何将指令传递到服务中?

Angularjs 如何将指令传递到服务中?,angularjs,Angularjs,当我从控制器将其作为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>'

当我从控制器
将其作为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>'
    };
});
如何更改指令以便能够通过:
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>'
    };
});
app.directive('codeblock',function(){
返回{
scope:true,//使用从父级继承的子作用域
限制:“A”,
替换为:“false”,
模板:“{stateService.message}}”
};
});

但我不知道如何更改指令,以便传入stateService,以及如何调用它。非常感谢您的帮助。

您可以将所需内容传递给指令

app.directive('codeblock', function() {
    return {
    scope: {
        stateService:"="
     },  // use a child scope that inherits from parent
    restrict: 'A',
    replace: 'false',
    template: '<div>{{ stateService.message }}</div>'
    };
});
app.directive('codeblock',function(){
返回{
范围:{
状态服务:“=”
},//使用从父级继承的子作用域
限制:“A”,
替换为:“false”,
模板:“{stateService.message}}”
};
});
在HTML中

<div codeblock  state-service="stateService"></div>

如果是
服务
,请将其传入,就像将服务传递给控制器一样

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;
      }
    };
}]);
app.directive('codeblock',['stateService',function(stateService){
返回{
scope:true,//使用从父级继承的子作用域
限制:“A”,
替换为:“false”,
模板:“{stateService.message}}”,
链接:函数(范围、元素、属性){
scope.stateService=stateService;
}
};
}]);

服务是单例的,不需要通过DOM传递它。

当我调用此指令时,我需要执行还是可以?两者都不需要。您有
restrict:'A'
,这意味着该指令只能用作属性<代码>
。如果要将其用作元素,则需要
限制:“E”
。如果你这样做,我就遇到了自动关闭自定义标记和HTML5验证程序的问题,我个人更喜欢
。请注意,如果你计划支持IE8,你需要采取额外的步骤才能将其用作元素。看见我个人认为使用指令作为元素弊大于利,但这是我个人的观点。所以可以这样称呼它:?@SamanthaJ应该是的,是的,但既然你问我,我怀疑你尝试时出了问题?
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;
      }
    };
}]);