trigger function after ng-repeat

2020-05-06 11:13发布

问题:

I am new to Angular, and I would like to do a really basic example. After displaying some data with a ng-repeat, I would like to use some of those data with javascript functions. But I don't know when to execute the javascript, because I don't when angular will finish to display my data.

Here is a fiddle: I try to show an alert with the function getAssign3 some data displayed by Angular. When should I call this function ?

Code:

<div ng-app="Test">
    <h1>Results Table</h1>
    <div ng-controller="AssignmentCtrl">
          <span ng-repeat="assign in assignments">
             <span id="{{assign.id}}">{{assign.title}}</span>
              <br/> 
        </span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>

More code:

var test = angular.module("Test", []);

function AssignmentCtrl($scope, $http, $timeout) {
    $scope.fetch = function () {
        // -- Mock server data..
        var data = [{id: 1,title: "Math 1",
                    },{id: 2, title: "Math 2",
                    }, { id: 3,title: "Math 3",
                    }];
         $scope.assignments = data;
    };
    $scope.fetch();
}

getAssign3 = function(){
    var dd = $("#3").text(); 
    alert(dd);
}
getAssign3();

回答1:

You have to add a $on catcher in your controller:

$scope.$on('ngRepeatFinished'), function (ngRepeatFinishedEvent) {
      console.log "After loop";
}

A directive in your app.js:

.directive('onFinishRender', function($timeout) {
    return {
      restrict: 'A',
      link: function(scope, element, attr) {
        if (scope.$last) {
          return $timeout (function() {
            scope.$emit 'ngRepeatFinished'
          });
       }
    }
})

and in your view:

on-finish-render="myFunc()"