我最终最终为它编写了自己的指令。我需要确保 gridster 可以看到对基础数据的每一次更改,但同时,我不想在数据模型上编写自己的监控,并用一个指令替换你通常在 gridster 中所做的一切隐藏所有这些。(这将涉及在指令本身内实现大部分 ng-repeat 。)
这就是我所拥有的(并假设“foo”是我的模块的名称):
foo.directive "gridster", () -> {
restrict: "E"
template: '<div class="gridster"><div ng-transclude/></div>'
transclude: true
replace: true
controller: () ->
gr = null
return {
init: (elem) ->
ul = elem.find("ul")
gr = ul.gridster().data('gridster')
return
addItem: (elm) ->
gr.add_widget elm
return
removeItem: (elm) ->
gr.remove_widget elm
return
}
link: (scope, elem, attrs, controller) ->
controller.init elem
}
foo.directive "gridsterItem", () -> {
restrict: "A"
require: "^gridster"
link: (scope, elm, attrs, controller) ->
controller.addItem elm
elm.bind "$destroy", () ->
controller.removeItem elm
return
}
有了这个,我可以有一个 gridster 生成的视图,通过添加这个:
<gridster>
<ul>
<li ... ng-repeat="item in ..." gridster-item>
<!-- Have something here for displaying that item. -->
<!-- In my case, I'm switching here based on some item properties. -->
</li>
</ul>
</gridster>
每当在 ng-repeat 指令观察到的集合中添加或删除项目时,它们将自动从 gridster 控制的视图中添加和删除。
编辑
这是一个演示该指令的略微修改版本的plunk :
angular.module('ngGridster', []);
angular.module('ngGridster').directive('gridster', [
function () {
return {
restrict: 'E',
template: '<div class="gridster"><div ng-transclude/></div>',
transclude: true,
replace: true,
controller: function () {
gr = null;
return {
init: function (elem, options) {
ul = $(elem);
gr = ul.gridster(angular.extend({
widget_selector: 'gridster-item'
}, options)).data('gridster');
},
addItem: function (elm) {
gr.add_widget(elm);
},
removeItem: function (elm) {
gr.remove_widget(elm);
}
};
},
link: function (scope, elem, attrs, controller) {
var options = scope.$eval(attrs.options);
controller.init(elem, options);
}
};
}
]);
angular.module('ngGridster').directive('gridsterItem', [
function () {
return {
restrict: 'EA',
require: '^gridster',
link: function (scope, elm, attrs, controller) {
controller.addItem(elm);
elm.bind('$destroy', function () {
controller.removeItem(elm);
});
}
};
}
]);