Angular指令第二个参数,为什么它是一个函数?

cap*_*ght 1 directive angularjs

这只是关于Angular指令的一般问题.为什么angular选择具有返回对象的函数而不仅仅直接将对象列为第二个参数?

换句话说,为什么它看起来像这样:

app.directive('helloWorld', function() {
  return {
    restrict: 'AE',
    replace: 'true',
    template: '<h3>Hello World!!</h3>'
  };
});
Run Code Online (Sandbox Code Playgroud)

而不是这个:

app.directive('helloWorld',{
    restrict: 'AE',
    replace: 'true',
    template: '<h3>Hello World!!</h3>'
});
Run Code Online (Sandbox Code Playgroud)

Del*_*lta 5

所以你可以注入依赖项

例如:

app.directive('helloWorld', function($rootScope) {
  return {
    restrict: 'AE',
    replace: 'true',
    template: '<h3>Hello World!!</h3>'
  };
});
Run Code Online (Sandbox Code Playgroud)

angular会将$ rootScope注入到你的指令中.