我正在尝试使用angular-gridster模块创建基于angularjs的Web仪表板。 gridster工作正常,我没有任何问题将内容绑定到它(如文本或图像与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 }
];
如果这是一个愚蠢的问题,我还是角色的初学者,请原谅我......
添加javascript和html元素有什么好方法?指令?自己的模块?但是如何?
感谢您的帮助!
答案 0 :(得分:2)
为了添加动态内容,您必须为每个小部件创建自定义指令,然后在您的gridItems对象中引用它们,您将在gridster网格上重复这些内容。
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撰写的题为“使用AngularJS建立SPA框架
的多边性课程”