Javascript AngularJS是否可以直接使用通过html作用域注入的服务?
我有这个指示:Javascript AngularJS是否可以直接使用通过html作用域注入的服务?,javascript,angularjs,angularjs-directive,angularjs-scope,angularjs-service,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Service,我有这个指示: app.directive("saveButton", ($rootScope, ConfirmationModal) => { return { templateUrl: "/structure/header/components/save-button/save-button.html", scope: true, link: function($scope, element, attrs) { $scope.Confirmat
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;
}
}
});
<button ng-click="ConfirmationModal.default()">
Click here
</button>
我有这个指令的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;
}
}
});
<button ng-click="ConfirmationModal.default()">
Click here
</button>
上面的操作正常,但请注意,在指令JS文件中
我已将服务附加到作用域:$scope.ConfirmationModal=ConfirmationModal
我的问题是,这是否可以使服务在没有附件的情况下可用?首先,我认为您实际上不应该直接使用服务。我认为angular方法更像是在控制器/组件内部使用服务 简短的回答是否定的。没有附件就无法提供服务。但我们假设您需要直接使用它,所以是的,您需要将它绑定到范围。就像你在这里做的一样 但是,如果您真的不想在这里绑定它,则不能在父控制器/组件中绑定它。默认情况下,该指令继承父级$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")
总之,我建议在这里使用component-over指令,因为它是“statefull”,而且会更方便。然后在组件的控制器内使用服务。并在控制器内使用类似于提交函数和调用服务的功能,并仅绑定到此提交的范围
希望有帮助,
干杯
参考资料:可能不适合您的场景,但您的save button指令是否有诸如“Modal”之类的父指令?您可能能够在父指令中初始化控制器,如controller:function{this.default=function{…},并使用CTRL[0]访问它。在子指令中,通过在attrsNo之后注入CTRL来进行默认。如果没有在JS中进行初始化,则无法使用。