Angular 将范围变量从控制器移动到指令

Angular moving scope variable from controller to directive

我创建了一个这样的指令

  .directive('optionLabel', function() {
    'use strict';
    return {
      replace: true,
      restrict: 'AE',
      template: '<div class="error-msg col-xs-12 intelligent-group col-centered"><h1 translate>{{ optionLabel }}</h1></div>'
    };
  })

现在,Scope optionLabel 设置在每个使用此指令的控制器中。

$scope.optionLabel = labelService.getOptionLabel(search.searchType);

我如何直接在指令中设置它,而不是像在 5 个控制器中重复执行此代码?

您可以使用 link,您可以在其中访问您的范围:

.directive('optionLabel', function() {
'use strict';
return {
  replace: true,
  restrict: 'AE',
  template: '<div class="error-msg col-xs-12 intelligent-group col-centered"><h1 translate>{{ optionLabel }}</h1></div>',
link: function(scope, element, attrs) {
scope.optionLabel = labelService.getOptionLabel(search.searchType);
};
})

不要忘记在指令中注入 labelService。