如何为Freewall jQuery插件创建Angular指令

时间:2017-06-09 17:19:17

标签: jquery angularjs angularjs-directive freewalljs

我需要在指令中执行一些jquery,我是新的角度,我不知道如何做到这一点。

var temp = "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(i/photo/{index}.jpg)'></div>";
        var w = 1, html = '', limitItem = 49;
        for (var i = 0; i < limitItem; ++i) {
            w = 200 +  200 * Math.random() << 0;
            html += temp.replace(/\{height\}/g, 200).replace(/\{width\}/g, w).replace("{index}", i + 1);
        }
        $("#freewall").html(html);

        var wall = new Freewall("#freewall");
        wall.reset({
            selector: '.cell',
            animate: true,
            cellW: 20,
            cellH: 200,
            onResize: function() {
                wall.fitWidth();
            }
        });
        wall.fitWidth();
        // for scroll bar appear;
        $(window).trigger("resize");
        }

这是你可以在https://github.com/kombai/freewall中查看的查询,我需要在angular指令中执行它,或者如果你知道更多的效率方法,你可以在这里分享它

2 个答案:

答案 0 :(得分:0)

我不确定您的要求(您是否需要将数据或回调传递给此指令?)。但是创建调用第三方插件的指令的一般方法是这样的:

var app = angular.module('yourApp', []);

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            if (!attrs.id) {
                return;
            }

            var temp = "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(i/photo/{index}.jpg)'></div>";
            var w = 1, html = '', limitItem = 49;
            for (var i = 0; i < limitItem; ++i) {
                w = 200 + 200 * Math.random() << 0;
                html += temp.replace(/\{height\}/g, 200).replace(/\{width\}/g, w).replace("{index}", i + 1);
            }
            elem.html(html);

            var wall = new Freewall("#" + attrs.id);
            wall.reset({
                selector: '.cell',
                animate: true,
                cellW: 20,
                cellH: 200,
                onResize: function () {
                    wall.fitWidth();
                }
            });
            wall.fitWidth();
            // for scroll bar appear;
            $(window).trigger("resize");
        }
    };
});

<div your-directive id="freewall"></div>

请注意,如评论中所述,如果您以后需要在单元格中添加Angular指令,则必须告诉Angular编译生成的html(或者使用翻译)。

答案 1 :(得分:0)

app.directive('theFreewall', function() {
  return function(scope, element, attrs) {
    scope.$on('LastBrick', function(event){
      var wall = new freewall("#freewall");
      wall.reset({
        selector: '.brick',
        animate: true,
        cellW: 200,
        cellH: 'auto',
        onResize: function() {
          wall.fitWidth();
        }
      });
      wall.container.find('.brick img').load(function() {
        wall.fitWidth();
      });
    });
  };
});

有关详细信息,请参阅GitHub: FreeWall Issue #142