trigger function after ng-repeat

妖精的绣舞 提交于 2019-12-02 18:46:20

问题


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()"


来源:https://stackoverflow.com/questions/20243427/trigger-function-after-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!