【问题标题】:How to render {{ }} during ng-repeat?如何在 ng-repeat 期间渲染 {{ }}?
【发布时间】:2015-11-22 08:38:59
【问题描述】:

考虑以下指令:

.directive('otherDirective', function(){
  return {
    link: function(scope, elem, attr){
      console.log(elem[0]);
      alert(elem[0]);
    }

  }

如果我将它应用到 ng-repeat 标记中,我会注意到直到 ng-repeat 结束(当被alert() 阻止时)才会评估 {{item}}。如何在每个“循环”之后渲染它?

因为在实际场景中,这些项目包含一个图像,我想在每个图像加载后做回调,但是没有 img url 我无法绑定事件。

here is the plunker

【问题讨论】:

  • 你需要等到ng-repeat完成它的渲染..

标签: javascript angularjs events dom angularjs-directive


【解决方案1】:

我认为您正在通过ng-repeat 范围变量{{x}} 分配img src。在这种情况下,如果您真的对加载图像元素感兴趣,您可以简单地输入onload 事件。我建议您使用on('load', funnction(){ //code }) 事件。每当图像加载到 DOM 时,此事件都会调用函数。

代码

.directive('otherDirective', function() {
    return {
      link: function(scope, elem, attr) {
        //element before loading
        console.log(elem[0]);
        elem.find('img').on('load', function() {
          //element after loaded
          console.log(elem[0]);
          //if you are going to manipulate scope binding here
          //then you have to run digest cycle manually
          //as this event will considered as outside of angular context
          //after binding/DOM manipulation is done..do apply digest by doing scope.$apply()
        })
      }
    }
});

Demo Plunkr

【讨论】:

  • 不错的$timeout-less 解决方案
  • @WouterHuysentruit Yepp..因为 OP 对图像加载的回调更感兴趣..然后我的回答涵盖了他想要的内容...... :)
【解决方案2】:

使用$timeout 等待ng-repeat 完成:Plunker

.directive('otherDirective',['$timeout', function($timeout){
  return {
    link: function(scope, elem, attr){
      $timeout(function () {
        console.log(elem[0]);
        alert(elem[0]);
      });
    }
  };
}]);

【讨论】:

  • 我认为这是一个合适的..安全运行摘要循环+1
猜你喜欢
  • 2014-09-19
  • 2014-01-16
  • 2017-01-26
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 2014-07-06
相关资源
最近更新 更多