210

テーブルを使用してdivをターゲットとするjQuery関数を呼び出したい。そのテーブルには。が入力されng-repeatます。

私がそれを呼ぶとき

$(document).ready()

結果はありません。

また

$scope.$on('$viewContentLoaded', myFunc);

助けにはなりません。

ng-repeatポピュレーションが完了した直後に関数を実行する方法はありますか?カスタムの使用に関するアドバイスを読みましたがdirective、ng-repeatと私のdivでそれを使用する方法がわかりません...

4

15 に答える 15

243

実際、ディレクティブを使用する必要があり、ng-Repeatループの終わりに関連付けられたイベントはありません(各要素は個別に構築され、独自のイベントがあるため)。ただし、a)ディレクティブを使用するだけで十分な場合があり、b)「onngRepeatfinished」イベントを作成するために使用できるng-Repeat固有のプロパティがいくつかあります。

具体的には、テーブル全体にイベントのスタイルを設定/追加するだけの場合は、すべてのngRepeat要素を含むディレクティブで使用できます。一方、各要素を具体的にアドレス指定する場合は、ngRepeat内でディレクティブを使用でき、作成後に各要素に作用します。

次に、イベントをトリガーするために使用できる、、、およびプロパティが$indexあります。したがって、このHTMLの場合:$first$middle$last

<div ng-controller="Ctrl" my-main-directive>
  <div ng-repeat="thing in things" my-repeat-directive>
    thing {{thing}}
  </div>
</div>

次のようなディレクティブを使用できます。

angular.module('myApp', [])
.directive('myRepeatDirective', function() {
  return function(scope, element, attrs) {
    angular.element(element).css('color','blue');
    if (scope.$last){
      window.alert("im the last!");
    }
  };
})
.directive('myMainDirective', function() {
  return function(scope, element, attrs) {
    angular.element(element).css('border','5px solid red');
  };
});

このプランカーで実際の動作を確認してください。それが役に立てば幸い!

于 2012-11-20T11:51:09.967 に答える
69

ループの最後でコードを実行したいだけの場合は、追加のイベント処理を必要としない、少し単純なバリエーションを次に示します。

<div ng-controller="Ctrl">
  <div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
    thing {{thing}}
  </div>
</div>
function Ctrl($scope) {
  $scope.things = [
    'A', 'B', 'C'  
  ];
}

angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      // iteration is complete, do whatever post-processing
      // is necessary
      element.parent().css('border', '1px solid black');
    }
  };
});

ライブデモをご覧ください。

于 2012-12-08T06:36:04.657 に答える
65

特にng-repeat完全なイベントを発生させるためだけにディレクティブを作成する必要はありません。

ng-initあなたのために魔法をします。

  <div ng-repeat="thing in things" ng-init="$last && finished()">

これは、最後の要素がDOMにレンダリングされたときにのみ発生$lastすることを確認します。finished

$scope.finishedイベントを作成することを忘れないでください。

ハッピーコーディング!!

編集:2016年10月23日

finished配列に項目がないときにも関数を呼び出したい場合は、次の回避策を使用できます

<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>

ng-repeat要素の上部に上記の行を追加するだけです。配列に値がないかどうかを確認し、それに応じて関数を呼び出します。

例えば

<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">
于 2016-06-17T10:42:55.547 に答える
41

これは、trueの場合に指定された関数を呼び出す繰り返し実行ディレクティブです。呼び出された関数は、レンダリングされた要素のツールチップを初期化するなど、DOM操作を実行する前に、interval=0で$timeoutを使用する必要があることがわかりました。jsFiddle: http: //jsfiddle.net/tQw6w/

$ scope.layoutDoneで、$ timeout行をコメントアウトし、「NOTCORRECT!」のコメントを外してみてください。ツールチップの違いを確認するための行。

<ul>
    <li ng-repeat="feed in feedList" repeat-done="layoutDone()" ng-cloak>
    <a href="{{feed}}" title="view at {{feed | hostName}}" data-toggle="tooltip">{{feed | strip_http}}</a>
    </li>
</ul>

JS:

angular.module('Repeat_Demo', [])

    .directive('repeatDone', function() {
        return function(scope, element, attrs) {
            if (scope.$last) { // all are rendered
                scope.$eval(attrs.repeatDone);
            }
        }
    })

    .filter('strip_http', function() {
        return function(str) {
            var http = "http://";
            return (str.indexOf(http) == 0) ? str.substr(http.length) : str;
        }
    })

    .filter('hostName', function() {
        return function(str) {
            var urlParser = document.createElement('a');
            urlParser.href = str;
            return urlParser.hostname;
        }
    })

    .controller('AppCtrl', function($scope, $timeout) {

        $scope.feedList = [
            'http://feeds.feedburner.com/TEDTalks_video',
            'http://feeds.nationalgeographic.com/ng/photography/photo-of-the-day/',
            'http://sfbay.craigslist.org/eng/index.rss',
            'http://www.slate.com/blogs/trending.fulltext.all.10.rss',
            'http://feeds.current.com/homepage/en_US.rss',
            'http://feeds.current.com/items/popular.rss',
            'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'
        ];

        $scope.layoutDone = function() {
            //$('a[data-toggle="tooltip"]').tooltip(); // NOT CORRECT!
            $timeout(function() { $('a[data-toggle="tooltip"]').tooltip(); }, 0); // wait...
        }

    })
于 2013-04-21T18:18:30.527 に答える
30

ng-initこれは、カスタムディレクティブを必要としない簡単なアプローチです。これは、特定のシナリオでうまく機能しました。たとえば、ページの読み込み時にng-repeatedアイテムのdivを特定のアイテムに自動スクロールする必要があるため、スクロール関数はng-repeat、DOMへのレンダリングが完了するまで待機してから起動する必要があります。

<div ng-controller="MyCtrl">
    <div ng-repeat="thing in things">
        thing: {{ thing }}
    </div>
    <div ng-init="fireEvent()"></div>
</div>

myModule.controller('MyCtrl', function($scope, $timeout){
    $scope.things = ['A', 'B', 'C'];

    $scope.fireEvent = function(){

        // This will only run after the ng-repeat has rendered its things to the DOM
        $timeout(function(){
            $scope.$broadcast('thingsRendered');
        }, 0);

    };
});

これは、ng-repeatが最初にレンダリングされた後に1回呼び出す必要がある関数にのみ役立つことに注意してください。ng-repeatの内容が更新されるたびに関数を呼び出す必要がある場合は、このスレッドでカスタムディレクティブを使用して他の回答のいずれかを使用する必要があります。

于 2014-07-18T05:34:05.397 に答える
28

Pavelの答えを補足すると、より読みやすく、簡単に理解できるものは次のようになります。

<ul>
    <li ng-repeat="item in items" 
        ng-init="$last ? doSomething() : angular.noop()">{{item}}</li>
</ul>

angular.noopそもそもなぜ他にあると思いますか...?

利点:

このためのディレクティブを書く必要はありません...

于 2015-07-02T14:38:59.790 に答える
21

たぶん、カスタムディレクティブを必要としないngInitLodashの方法を使用した少し簡単なアプローチ:debounce

コントローラ:

$scope.items = [1, 2, 3, 4];

$scope.refresh = _.debounce(function() {
    // Debounce has timeout and prevents multiple calls, so this will be called 
    // once the iteration finishes
    console.log('we are done');
}, 0);

レンプレート:

<ul>
    <li ng-repeat="item in items" ng-init="refresh()">{{item}}</li>
</ul>

アップデート

三項演算子を使用したさらに単純な純粋なAngularJSソリューションがあります。

レンプレート:

<ul>
    <li ng-repeat="item in items" ng-init="$last ? doSomething() : null">{{item}}</li>
</ul>

ngInitはリンク前のコンパイルフェーズを使用することに注意してください。つまり、子ディレクティブが処理される前に式が呼び出されます。これは、非同期処理が必要になる可能性があることを意味します。

于 2014-11-21T10:06:14.250 に答える
4

scope.$last変数をチェックしてトリガーを。でラップする場合にも必要になる場合がありますsetTimeout(someFn, 0)。AsetTimeout 0はjavascriptで受け入れられている手法であり、directive正しく実行することが不可欠でした。

于 2013-09-20T19:43:28.460 に答える
4

私はこのようにしました。

ディレクティブを作成する

function finRepeat() {
    return function(scope, element, attrs) {
        if (scope.$last){
            // Here is where already executes the jquery
            $(document).ready(function(){
                $('.materialboxed').materialbox();
                $('.tooltipped').tooltip({delay: 50});
            });
        }
    }
}

angular
    .module("app")
    .directive("finRepeat", finRepeat);

このng-repeatのラベルに追加した後

<ul>
    <li ng-repeat="(key, value) in data" fin-repeat> {{ value }} </li>
</ul>

そして、それで準備ができて、ng-repeatの終わりに実行されます。

于 2016-05-17T04:32:12.590 に答える
4
<div ng-repeat="i in items">
        <label>{{i.Name}}</label>            
        <div ng-if="$last" ng-init="ngRepeatFinished()"></div>            
</div>

私の解決策は、アイテムが繰り返しの最後である場合に関数を呼び出すdivを追加することでした。

于 2017-05-25T21:41:13.687 に答える
3

これは、宣言型構文を使用してスコープを分離するときにngRepeatプロパティ($ index、$ first、$ middle、$ last、$even、$ odd)にアクセスする方法を示すために、他の回答で表現されたアイデアの改善です( Googleは、要素ディレクティブを使用したベストプラクティス)を推奨しました。主な違いに注意してくださいscope.$parent.$last

angular.module('myApp', [])
.directive('myRepeatDirective', function() {
  return {
    restrict: 'E',
    scope: {
      someAttr: '='
    },
    link: function(scope, element, attrs) {
      angular.element(element).css('color','blue');
      if (scope.$parent.$last){
        window.alert("im the last!");
      }
    }
  };
});
于 2015-01-23T18:21:59.957 に答える
2

上記の回答では、ngRepeatの実行後に実行する必要のあるコードは角度のあるコードであると見なされているため、別の回答を追加したいと思います。この場合、上記のすべての回答は、他の回答よりも一般的な、優れた単純なソリューションを提供します。ダイジェストのライフサイクルステージが重要な場合は、$evalの代わりに$parseを使用することを除いて、BenNadelのブログをご覧ください。

しかし、私の経験では、OPが述べているように、通常、最終的にコンパイルされたDOMでいくつかのJQueryプラグインまたはメソッドを実行します。その場合、setTimeout関数がプッシュされるため、最も簡単な解決策はsetTimeoutを使用してディレクティブを作成することです。ブラウザのキューの最後まで、すべてが角度で行われた直後、通常はngReapetであり、親のpostLinking機能の後に続きます。

angular.module('myApp', [])
.directive('pluginNameOrWhatever', function() {
  return function(scope, element, attrs) {        
    setTimeout(function doWork(){
      //jquery code and plugins
    }, 0);        
  };
});

その場合に$timeoutを使用しないのはなぜだろうと思っている人にとっては、それは完全に不要な別のダイジェストサイクルを引き起こすということです。

于 2015-12-28T15:39:51.700 に答える
1

ng-repeatが終了した後、MathJaxを使用して数式をレンダリングする必要がありましたが、上記の回答のいずれも問題を解決しなかったため、以下のように作成しました。それは良い解決策ではありませんが、私のために働きました...

<div ng-repeat="formula in controller.formulas">
    <div>{{formula.string}}</div>
    {{$last ? controller.render_formulas() : ""}}
</div>
于 2016-10-03T17:43:18.810 に答える
0

私はここでよく練習された答えを見つけましたが、それでも遅延を追加する必要がありました

次のディレクティブを作成します。

angular.module('MyApp').directive('emitLastRepeaterElement', function() {
return function(scope) {
    if (scope.$last){
        scope.$emit('LastRepeaterElement');
    }
}; });

次のように、属性としてリピーターに追加します。

<div ng-repeat="item in items" emit-last-repeater-element></div>

ラドゥによると、:

$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => {mycode});

私にとっては機能しますが、それでもsetTimeoutを追加する必要があります

$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => {
setTimeout(function() { 
    mycode
}, 100); });
于 2018-04-20T16:32:10.913 に答える
-4

クラス名を変更してレンダリングが異なるようにするだけの場合は、以下のコードでうまくいきます。

<div>
<div ng-show="loginsuccess" ng-repeat="i in itemList">
    <div id="{{i.status}}" class="{{i.status}}">
        <div class="listitems">{{i.item}}</div>
        <div class="listitems">{{i.qty}}</div>
        <div class="listitems">{{i.date}}</div>
        <div class="listbutton">
            <button ng-click="UpdateStatus(i.$id)" class="btn"><span>Done</span></button>
            <button ng-click="changeClass()" class="btn"><span>Remove</span></button>
        </div>
    <hr>
</div>

このコードは、ショッピングリスト内の買い物済みアイテムをStrickトラフフォントでレンダリングするという同様の要件がある場合に機能しました。

于 2015-04-20T04:35:51.423 に答える