AngularJS 在执行指令之前等待项目的最后一次加载

AngularJS Wait the last loading of an item before execute a directive

我在 AngularJs 上遇到了一个问题,我无法解决。 (我是 Angular 的新手)。

我有一个容器指令、一个页面指令和一个内容指令。

<container>
  <page>
    <contents></contents>
  </page>
  <page></page>
  <page></page>
  <!-- ... -->
</container>

在每个页面上,link函数将MasterService(工厂)的页面数附加1

app.directive('page', function(Master) {
    return {
        restrict: 'E',
        template: '<div ng-transclude></div>',
        transclude: true,
        scope: {},
        link: function(scope, element, attrs) {
            Master.pages ++;
        }
    }
});

然而,此代码有效,当调用内容函数(此函数将在第 1 或第 2 页)以获取 Master.page 时,我只得到 1 或 2,因为下一页不是分析。我发现的唯一方法是在我想要 Master.pages

时执行 $timeout

$timeout(function() {
  console.log(Master.pages);
}, 2000);

但我不喜欢那样,我怎么能在所有页面加载后调用一个函数?

谢谢

因为您正在使用嵌入,所以编译顺序、pre-link 和 post-link 已更改。 (参见 Angular 文档)

而不是使用 link 尝试像这里一样使用编译:这样你的计数器将在 link 前阶段递增。

app.directive('page', function(Master) {
    return {
        restrict: 'E',
        template: '<div ng-transclude></div>',
        transclude: true,
        scope: {},
        compile: function(tElem, tAttrs){
        
        return {
          pre: function(scope, iElem, iAttrs){
            Master.pages ++;
          },
          post: function(scope, iElem, iAttrs){
            
          }
        }
      }

    }
});

只想提供@user1802646 的另一种想法。

您是如何生成页面的?如果它们是数据驱动的,你可以使用 ng-repeat 吗?您也许可以让 "ng-repeat-end" 的用户获得您想要的正确时间。