【问题标题】:Angularjs directive wrapping ng-repeatAngularjs 指令包装 ng-repeat
【发布时间】:2014-06-23 08:35:17
【问题描述】:

这里是一个 Angularjs 新手。

我正在尝试在我的 Angularjs 应用程序中使用 Justified gallery

这里是JS Fiddle describing the problem

Justified Gallery 是一个 jquery 插件,所以我创建了指令来调用它:

app.directive('justified', function () {
    return {
        restrict: 'AE',
        link: function (scope, el, attrs) {
            $(el).justifiedGallery();
        }
    };
});

确实,它可以很好地处理静态定义的内容(例如,小提琴中 html 的注释部分)。但是一旦我尝试将它与 ng-repeat 一起使用,就像这里一样:

   <div justified id="justified"> 
        <a ng-repeat="dir in dirs" ng-href="/#/dir/{{dir.id}}">
          <img ng-src="{{dir.first_image}}" alt="{{dir.name}}"/>
        </a>
    </div justified>

什么都没有发生,什么都没有被渲染。我相信这与 ng-repeat 中的范围有关,但我无法找出解决问题的正确方法。

谁能指出我的错误在哪里?

非常感谢。

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    您可以使用自定义指令来找出重复何时完成渲染,例如从这个SO answer

    app.directive('repeatDone', [function () {
      return {
        restrict: 'A',
         link: function (scope, element, iAttrs) {
              var parentScope = element.parent().scope();
              if (scope.$last){
                   parentScope.$last = true;           
              }
            }
          };
        }]);
    

    我更新了你的小提琴:http://jsfiddle.net/xjZ8N/1

    编辑
    我必须添加一个 $timeout 以便 angular 可以在调用画廊函数之前更新 html。

    【讨论】:

    • 非常感谢!不过有一个问题——传递给 $watch 的函数中的 n 和 o 参数是什么?
    • @mkowalik - 该函数从 Angular 获取两个参数 - 新值和旧值。我们希望在“新”值为真时设置画廊。有意义吗?
    • 绝对可以。谢谢。
    • 我遇到了同样的问题,正是这个解决方案有所帮助。
    • 为什么你用 'if(scope.$last)' 保护,这个保护不应该用 'if(parentScope)' 保护,因为这是你正在操作的东西?
    【解决方案2】:

    Simple way:

    app.directive('justified', function ($timeout) {
        return {
            restrict: 'AE',
            link: function (scope, el, attrs) {
                $timeout($(el).justifiedGallery);
            }
        };
    });
    

    【讨论】:

    • 似乎有理由在 ng-repeat 完成渲染元素之前启动画廊。
    • 谢谢,我已经考虑过了并尝试手动设置指令优先级 - ng-repeat 的优先级为 1000,所以我将 justified 设置为较低的值,但它没有帮助。顺便说一句,我修改了your solution ( $timeout($(el).justifiedGallery()); 而不是 $timeout($(el).justifiedGallery); ),但不幸的是无济于事..
    • 我认为,如果将justifiedng-repeat 附加到同一个元素上会有所帮助。
    • $timeout 接受一个函数并在超时后执行它(在这种情况下为 0)。如果你执行$timeout($(el).justifiedGallery()); - 你立即执行justifiedGallery 并将它的返回值传递给$timeout - 没有用。
    • 感谢您的解释 - 这是有道理的,我不得不承认我没有阅读 $timeout 的文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2014-11-07
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多