{ return { templateUrl:-6ren">
gpt4 book ai didi

javascript - AngularJS 是否可以直接使用通过 html 范围注入(inject)的服务?

转载 作者:行者123 更新时间:2023-12-03 00:48:25 24 4
gpt4 key购买 nike

我有这个指令:

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;

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

最佳答案

首先,我认为你不应该直接使用服务。我认为 Angular 方式更像是在 Controller /组件内部使用服务。

简短的回答是否定的。如果没有附件,则无法提供该服务。但是我们假设您需要直接使用它,所以是的,您需要将它绑定(bind)到作用域。就像您已经在这里所做的那样。

但是,如果您真的不想在此处绑定(bind)它,则无法在父 Controller /组件中绑定(bind)它。默认情况下指令继承父级 $scope,因此您可以在父级中绑定(bind)它一次,该父级( Controller 或组件)内的所有“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")

总而言之,我建议在这里使用组件而不是指令,因为它是“有状态的”,而且会方便得多。然后在组件的 Controller 内使用服务。并使用类似 Submit() 函数并在 Controller 内调用服务,并仅绑定(bind)到此提交的范围。

希望对你有帮助干杯。

引用文献:https://docs.angularjs.org/guide/directive

关于javascript - AngularJS 是否可以直接使用通过 html 范围注入(inject)的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53151877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com