我的目标是创建一个显示弹出对话框消息的角度模块。该模块包含一个指令(HTML、CSS和JavaScript),其中包含内部逻辑(以及标记和样式)。此外,还有一个服务(工厂),它充当其他服务可以使用的API。
现在,这个服务当然有了一个openDialog()函数,它应该将对话框指令插入DOM并呈现给用户。
到目前为止,我发现的所有解决这个问题的方法都使用了$compile函数。但它需要scope作为参数。但是,在没有scope的服务中。它们只存在于controller或link函数中。
选择此实现的原因是为了分离关注点(指令的link和controller用于内部使用,factory用于外部使用,因为可以注入依赖项)。我知道在像这样调用函数时可以传递scope:
popupDialogService.openDialog({ /* options */ }, $scope);但我不明白重点。感觉不太对劲。如果我在不使用scope的另一个服务中调用该函数,该怎么办?
是否有一种方法可以轻松地将指令从服务函数中放入DOM,或者有更好的方法来解决这个问题?
我正在考虑的另一个解决方案是从指令的controller内部调用指令的factory函数。这有可能吗?
代码
popupDialog.directive.js
angular.module('popupDialog').directive('popupDialog', directive);
function directive() {
return { ... };
}popupDialog.service.js
angular.module('popupDialog').factory('popupDialogService', factory);
function factory() {
return { openDialog, closeDialog }; // *ES2015
function openDialog(options) {
// this function should put the `popupDialog` directive into the DOM
}
function closeDialog() {
// and this one should remove it
}
}some.random.service.js
angular.module('myApp').factory('someRandomService', factory);
factory.$inject = ['popupDialogService'];
function factory(popupDialogService) {
return { clickedButton };
function clickedButton() {
popupDialogService.openDialog({ /* options */ });
// Sample implementation.
// It shouldn't matter where this function is beeing called in the end.
}
}发布于 2015-08-23 07:57:38
我知道我可以在调用函数时传递范围.感觉不太对劲。
无论如何,您需要对话框HTML内容的作用域,角需要在某个范围内编译和呈现它,对吗?因此,您必须以某种方式为模板提供范围对象。
我建议您看一看流行的模态实现,例如角UI引导程序的$modal或我为我的需求创建的简单的。常见的模式是通过模式初始化传递作用域参数,或者使用$rootScope的新子作用域进行对话框。这是最灵活的方式,应该适用于你的两种情况。
毕竟,它不一定必须是真正的范围实例。您甚至可以让您的服务接受普通的javascript对象,并使用它来扩展新的$rootScope.$new()对象。
https://stackoverflow.com/questions/32164237
复制相似问题