首页 > 解决方案 > AngularJS 是否可以直接使用通过 html 范围注入的服务?

问题描述

我有这个指令:

app.directive("saveButton", ($rootScope, ConfirmationModal) => {
  return {
    templateUrl: "/structure/header/components/save-button/save-button.html",
    scope: true,
    link: function($scope, element, attrs) {

      $scope.ConfirmationModal = ConfirmationModal;

    }
  }
});

我有这个指令的 HTML 模板:

<button ng-click="ConfirmationModal.default()">
  Click here
</button>

以上工作正常,但请注意,在指令 JS 文件中,我已将服务附加到范围:$scope.ConfirmationModal = ConfirmationModal;.

我的问题是,这是否可以在没有附件的情况下提供服务?

标签: javascriptangularjsangularjs-directiveangularjs-scopeangularjs-service

解决方案


首先,我认为您不应该直接使用服务。我认为角度方式更喜欢在控制器/组件中使用服务。

简短的回答是 No。没有附件就无法提供服务。但是让我们假设您需要直接使用它,所以是的,您需要将它绑定到范围。就像你已经在这里做的那样。

但是,如果你真的不想在这里绑定它,你不能在父控制器/组件中绑定它。默认情况下,指令是继承父 $scope,因此您可以在父级中绑定一次,所有在此父级(控制器或组件)中的“saveButton”指令也将拥有它。

angular.module('docsIsolateScopeDirective', [])
 .controller('ParentController', ['$scope','ConfirmationModal' function($scope, ConfirmationModal) {
 $scope.ConfirmationModal = ConfirmationModal;
}])
.directive('myCustomer', function() {
  return {
    templateUrl: '/structure/header/components/save-button/save-button.html'
  };
});

此外,您可以将特定范围变量传递给指令,如下所示:

scope: {
  ConfirmationModal: '=ConfirmationModal'
},

你把它从父母那里传过去

save-button(confirmation-modal="$ctrl.confirmationModal")

所以总而言之,我建议在这里使用组件而不是指令,因为它是'statefull',它会更方便。然后在组件的控制器内使用服务。并使用类似 submit() 函数并在控制器内调用服务,并仅绑定到此提交的范围。

希望它有帮助,干杯。

参考资料:https ://docs.angularjs.org/guide/directive


推荐阅读