How do you execute directive code after rendering?

你。 提交于 2019-12-06 07:10:38

问题


I'm trying to build a directive that runs after a nested ng-repeat has completed rendering. Here's what I've tried (fiddle):

The HTML:

<div ng-app="MyApp" ng-controller="MyCtrl">
    <ul my-directive>
        <li ng-repeat="animal in animals">{{animal}}</li>
    </ul>
</div>

And the JavaScript:

angular.module("MyApp", [])
    .directive("myDirective", function () {
        return function(scope, element, attrs) {
            alert(element.find("li").length); // 0
        };
    });

function MyCtrl($scope) {
    $scope.animals = ["Dog", "Cat", "Elephant"];
}

The linking function in my custom directive runs before all of the <li> elements have been rendered (and 0 is alerted). How do I run code after the ng-repeat has completed rendering?


回答1:


You could move the directive inside ng-repeat, http://jsfiddle.net/ZTMex/3/

<div ng-app="MyApp" ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="animal in animals" my-directive>{{animal}}</li>
    </ul>
</div>

Or have a look at https://stackoverflow.com/a/13472605/1986890 which is related to your question.



来源:https://stackoverflow.com/questions/14541829/how-do-you-execute-directive-code-after-rendering

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