gpt4 book ai didi

javascript - 在 Gridster 中动态添加 AngularJS 指令

转载 作者:行者123 更新时间:2023-12-02 14:47:47 24 4
gpt4 key购买 nike

我刚刚开始使用 AngularJS,但我发现了一个我无法找出的小问题,希望你们能帮助我。

我导入了 AngularJS Gridster,这是一种向网页添加动态网格的简单方法。现在一切正常,元素已成功从数据库加载并导入到 Gridster 中,但现在我想做以下事情。在从数据库检索的 JSON 中,还有一个名为“directive”的属性。现在,当所有内容都加载完毕后,我想在每个 Gridster 元素中添加从数据库返回的指令。

<ul>
<li gridster-item="item" ng-repeat="item in gridsterItems">
{{ item.directive }} // Returns <clock-widget></clock-widget> and print it to the screen, but it dont run the directive and doesn't display.
</li>
</ul>

现在它返回正确的值并在屏幕上显示字符串,但我想运行它指令clockWidget。

app.directive('clockWidget', function() {
return {
replace: true,
template: 'Yups, I am the clockwidget',
};
});

在互联网上我读到了一些关于 $compile 的内容,但我找不到。希望各位大佬能帮帮我。

谢谢!

最佳答案

是的,您需要使用$compile。请参阅documentation .

jsfiddle 上的实例.

angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.directives = ["<directive-one></directive-one>", "<directive-two val='inputVal'></directive-two>"];
})
.directive('compileDirective', function($compile) {
return {
restrict: "E",
replace: true,
link: function(scope, element, attr) {
scope.$watch(function() {
return attr.directive;
}, function(val) {
element.html("");
if (val) {
var directive = $compile(angular.element(val))(scope);
element.append(directive);
}
});
}
};
})
//Directives for example
.directive('directiveOne', function($compile) {
return {
replace: true,
template: "<div>i'm directive one</div>"
};
})
.directive('directiveTwo', function($compile) {
return {
replace: true,
scope:{val:"="},
template: "<div>i'm directive two with val={{val}}</div>"
};
})
.directive('directiveThree', function($compile) {
return {
replace: true,
scope:{val:"="},
template: "<div>i'm directive three</div>"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectDirective" ng-options="dir for dir in directives">
</select>
<input ng-model="inputVal">
<compile-directive directive="{{selectDirective}}"></compile-directive>
<compile-directive directive="<directive-three></directive-three>"></compile-directive>
</div>
</div>

关于javascript - 在 Gridster 中动态添加 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36448937/

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