[英]How can I add dynamic directives to my angular app on the fly?
我有一个需要模拟OS窗口类型行为的应用程序。 因此,我需要能够添加多个窗口,每个窗口都具有自己的上下文以及可能具有自己的嵌套指令。
我已经有一个windowDirective和userProfile指令,我想实例化每个实例的新实例,并根据需要将其添加或从dom中删除。
到目前为止,我一直试图通过WindowService使用$ compile来完成此任务,该编译实际上是在其中编译带有指令标记的字符串,即$compile("<window><user-profile></user-profile></window>")(scope)
,它似乎创建了一个dom树,但产生了很多错误。
关于如何处理这个问题有任何想法吗?
我做了类似的事情。
对于初学者,您需要创建一个指令,该指令将成为您的主容器(用于将其他窗口放置在其中)。 为该主容器分配一个控制器,该控制器将保留您计划插入/删除的所有其他子窗口的列表。 每当您想要销毁作用域和内存时,都需要使用它来清理作用域和内存。
var module = angular.module('myModule', []);
module.directive('myContainer', ContainerDirective);
function ContainerDirective() {
return {
restrict: 'E',
controller: ['$scope', '$element', '$compile', function ContainerController($scope, $element, $compile) {
var winId = 0;
this.subWindows = {};
//Create a window
this.createWindow = function() {
var subWinElem = angular.element('<my-window>');
this.subWindows[winId++] = subWinElem;
$element.append(subWinElem);
$compile(subWinElem)(scope);
subWinElem.data('window-id', winId);
return winId;
};
//Destroy a window
this.destroyWindow = function(winId) {
if(this.subWindows[winId]) {
var subWinElem = this.subWindows[winId],
subWinScope = subWinElem.scope();
subWinElem.remove();
subWinScope.$destoroy();
this.subWindows[winId] = null;
}
};
//Clean up on container destroy
this.dispose = function() {
angular.forEach(this.subWindows, function(subWinElem) {
if(subWinElem) {
var subWinScope = subWinElem.scope();
subWinElem.remove();
subWinScope.$destroy();
}
});
};
}],
link: function($scope, elem, attrs, ContainerController) {
//On click of a button you would create a sub window
scope.createWindow = function() {
ContainerController.createWindow();
};
//Cleanup anything left in the controller
$scope.$on('$destroy', function() {
ContainerController.dispose();
});
}
};
}
子窗口应该是“需要”父控制器的指令。 要动态调用它们,您可以做的是先附加指令标记,然后$ compile该元素的引用(好于$ compile('string'))。 因为先添加元素然后再进行编译,所以可以要求父控制器没有问题(因为它使用InheritedData)。
module.directive('myWindow', WindowDirective);
function WindowDirective() {
return {
restrict: 'E',
scope: true,
require: '?^myContainer',
link: function($scope, elem, attrs, ContainerController) {
var winId = elem.data('window-id');
//You would destroy window like so
$scope.$on('$destroy', function() {
ContainerController.destroyWindow(winId);
});
}
}
}
PS这是一个简化的示例(可能包含拼写错误:P),但是您可以理解要点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.