gpt4 book ai didi

javascript - 使用 AngularJS 在 Controller 中动态创建项目

转载 作者:行者123 更新时间:2023-11-30 00:03:31 25 4
gpt4 key购买 nike

我创建了一个自定义指令,如下所示。

 app.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {

}
};
});

我的 HTML 代码如下所示。

<ion-view view-title="Search">
<ion-content>
<div id="myid"></div>
</ion-content>
</ion-view>

最后,我的 Controller 如下所示。我想在 Controller 内动态创建 my-directive 元素,如下所示。但它不起作用。你知道解决这个问题的方法吗?提前致谢!!

app.controller('Search', function ($scope) {
var content = document.getElementById("myid");
content.setAttribute("class", "list");
var mydir = document.createElement("my-directive");

content.appendChild(mydir);
})

最佳答案

不确定这背后的原因是什么:

my template data coming from server dynamicly and using inside the controller is the best solution for me

嗯,不推荐,但是可以。请参见下面的示例:

var app = angular.module("sa", []);

app.controller("Search", function($scope, $compile) {

$scope.doTheBadThing = function() {
var $parent = angular.element(document.getElementById("myid"));
$parent.addClass("list");
var mydir = document.createElement("my-directive");
// or
//var mydir = "<my-directive></my-directive>";
$parent.append(mydir);

// This is the main thing. You need to compile the dynamic HTML so that Angular can initialized on those template
$compile($parent.contents())($scope);
};
});

app.directive('myDirective', function() {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function(scope, element, attrs) {

}
};
});
#myid {
background: #ccc;
min-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="Search">
<button ng-click="doTheBadThing()">Do the bad thing</button>
<div id="myid"></div>
</div>

关于javascript - 使用 AngularJS 在 Controller 中动态创建项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385556/

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