gpt4 book ai didi

angularjs - 具有不同动态内容的小部件(Angular-Gridster)

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

我正在尝试使用 Angular-Gridster 模块创建一个基于 AngularJS 的 Web 仪表板。 gridster 工作正常,我在将内容绑定(bind)到它时没有任何问题(例如使用 ng-bind-html 的文本或图像)。

但实际上我不想只向这些“小部件”添加文本或图像,我正在尝试创建一个包含动态内容的仪表板。因此,作为用户,我想向仪表板添加一个新的小部件并选择一种类型(例如时钟小部件或其他小部件),并可能配置该小部件。

问题是我不知道如何向小部件添加动态内容(javascript、不同的 html 元素...)。该小部件是在范围对象之外创建的,例如:

$scope.standardItems = [
{ name: "Item 1", content: "Text 1", sizeX: 2, sizeY: 1, row: 0, col: 0 },
{ name: "Item 2", content: "Clock widget", sizeX: 2, sizeY: 2, row: 0, col: 2 }
];

我仍然是 Angular 的初学者,所以如果这是一个愚蠢的问题,请原谅......

添加 javascript 和 html 元素的好解决方案是什么?指令?自己的模块?但如何呢?

感谢您的帮助!

最佳答案

为了添加动态内容,您必须为每个小部件创建自定义指令,然后在您将在 gridster 网格上 ng-repeat 的 standardItems 对象中引用它们。

scope.standardItems = [{
title: 'Clock Widget',
settings: {
sizeX: 3,
sizeY: 3,
minSizeX: 3,
minSizeY: 3,
template: '<clock-widget></clock-widget>',
widgetSettings: {
id: 1
}
}
}]

好的,您应该有一个用于 gridster 小部件定义的指令,其中包含一个带有自定义小部件定义的对象,也许还有一些默认的 gridster 选项。

我建议创建一个自定义 widgetBody 指令,所有自定义小部件都将引用该指令。该指令还将根据您设置小部件的样式来处理附加到每个小部件标题的自定义按钮。您还需要为指令创建关联的模板。

"use strict";
angular.module('myGridsterDashboard').directive('widgetBody', ['$compile',
function($compile) {
return {
templateUrl: 'widgetBodyTemplate.html',
link: function(scope, element, attrs) {
// create a new angular element from the resource in the
// inherited scope object so it can compile the element
// the item element represents the custom widgets
var newEl = angular.element(scope.item.template);
// using jQuery after new element creation, to append element
element.append(newEl);
// returns a function that is looking for scope
// use angular compile service to instanitate a new widget element
$compile(newEl)(scope);


}

}

}
]);

创建指令后,您需要在主模板中引用该指令,在主模板中为自定义小部件执行 gridster ng-repeat。

 <!-- reference your default gridster options if you created some -->
<div gridster="gridsterOpts">
<ul>
<li gridster-item="item" ng-repeat="item in standardItems">
<!-- created a custom directive to compile the widget body and keep it out of the dashboard object -->
<widget-body></widget-body>
</li>
</ul>

现在,通过继承,您创建的每个自定义小部件都将继承小部件主体,并将被编译并一一添加到 ng-repeat 指令内的 DOM 中。

希望这有帮助......- Mark Zamoyta 的 Pluralsight 类(class),题为“使用 AngularJS 构建 SPA 框架

关于angularjs - 具有不同动态内容的小部件(Angular-Gridster),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051059/

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