javascript - 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;
.
我的问题是,这是否可以在没有附件的情况下提供服务?
解决方案
首先,我认为您不应该直接使用服务。我认为角度方式更喜欢在控制器/组件中使用服务。
简短的回答是 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() 函数并在控制器内调用服务,并仅绑定到此提交的范围。
希望它有帮助,干杯。
推荐阅读
- java - 为什么 instanceof 和迭代单个列表比几个专门的列表更快?
- hive - 如何禁用 Hive 表的事务?
- c++ - 获取 std::tuple 元素作为 std::variant
- python - 将 Python 连接到 Oracle 数据库需要什么
- mysql - SQL计算来自两个不同表的计数之间的比率
- java - 如何仅用 4 位存储 0-9 范围内的整数,并使用与 HashMap 中的 Key 相同的值?
- python - 使用 Google Cloud Talent Solution (Python) 时如何导入类型
- c# - 有人知道为什么我在尝试处理反应时会收到此 NullReferenceException 错误吗
- database - DB2/IDAA:如何以毫秒为单位将 VARCHAR 正确格式化为 TIMESTAMP
- javascript - 解析cookie过期日期