gpt4 book ai didi

angularjs - 如何将 Controller 动态加载到指令

转载 作者:行者123 更新时间:2023-12-02 04:56:01 30 4
gpt4 key购买 nike

所以我有一个指令将在我的应用程序中充当侧面板。当用户单击按钮时,侧面板将打开。在所述侧面板中,我需要该区域的 Controller 和 View 根据用户单击的按钮是动态的。我找到了一种动态加载模板的方法,但我遇到了动态加载 Controller 的问题。

代码到此为止。

指令代码

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>

指令所在的 View Controller

$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';
};

最佳答案

您可以通过单击按钮广播(使用 $broadcast)事件。并在指令中有一个监听器(使用 $on)。这样,无论何时触发事件,都会执行指令逻辑。

$broadcast 和 $on 的用法可以引用这个链接的答案:

On-and-broadcast-in-AngularJS

关于angularjs - 如何将 Controller 动态加载到指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22230213/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com