【发布时间】:2014-04-09 10:14:54
【问题描述】:
所以我有一个指令将在我的应用程序中充当侧面板。当用户单击按钮时,侧面板将打开。在所述侧面板中,我需要该区域的控制器和视图根据用户单击的按钮是动态的。我找到了一种动态加载模板的方法,但我遇到了动态加载控制器的问题。
这里说的够多了,就是代码。
指令代码
app.directive('itemForm', function($compile) {
var item1Template = '<div ng-include="view"></div>';
var item2Template = '<h1> Hello item2 Form </h1>';
var getTemplate = function(contentType) {
if(contentType === 'item1') {
return item1Template;
} else if(contentType === 'item2') {
return item2Template;
}
};
return {
restrict: 'E',
replace: 'true',
scope: {
formType: '@formType'
},
//templateUrl: scope.template,
link: function(scope, element) {
if(scope.formType === 'item1') {
scope.view = '/views/item1.html';
}
element.html(getTemplate(scope.formType)).show();
$compile(element.contents())(scope);
}
};
});
HTML
<item-form form-type='{{form.type}}'> </item-form>
该指令所在视图的控制器
$scope.form = {};
$scope.openItemOneDlg = function() {
$scope.isFormOpen = !$scope.isFormOpen; // this opens the side panel
$scope.form.type = 'item1';
};
$scope.openItemTwoDlg = function() {
$scope.isFormOpen = !$scope.isFormOpen; // this opens the side panel
$scope.form.type = 'item2';
};
【问题讨论】:
-
模板可以通过使用指令对象的
template或templateURL属性在link函数之外动态加载。每个不仅可以采用静态值,还可以采用function(tElement, tAttrs) { ... }形式的函数 -
是的,模板不是我的问题,我已经很好地工作了,我无法分配控制器以与每个模板一起使用。
-
我在 11 月遇到了这个问题并在此处发布,我没有得到任何关于如何执行此操作的好的回复,仍然没有弄清楚。
-
这个答案能满足你的需要吗?我知道它是标签式但类似的概念:stackoverflow.com/questions/21162467/…
标签: angularjs angularjs-directive angularjs-controller