AngularJS: Fire an event immediately after $scope.$digest

前端 未结 3 1352
庸人自扰
庸人自扰 2021-02-04 06:58

In my AngularJS app, there\'s several points at which I want to wait for a $scope to be processed into the DOM, and then run some code on it, like a jquery fadeIn, for example.<

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 07:18

    In this jQuery fade-in-and-out fiddle (which I found it on the JSFiddles Examples wiki page), the author defines a "fadey" directive and performs the jQuery fadeIn (or fadeOut) in the directive's link function"

  • ... myApp.directive('fadey', function() { return { restrict: 'A', link: function(scope, elm, attrs) { var duration = parseInt(attrs.fadey); if (isNaN(duration)) { duration = 500; } elm = jQuery(elm); // this line is not needed if jQuery is loaded before Angular elm.hide(); elm.fadeIn(duration)
  • Another possible solution is to use $evalAsync: see this comment by Miško, in which he states:

    The asyncEval is after the DOM construction but before the browser renders. I believe that is the time you want to attach the jquery plugins. otherwise you will have flicker. if you really want to do after the browser render you can do $defer(fn, 0);

    ($defer was renamed $timeout).

    However, I think using a directive (since you are manipulating the DOM) is the better approach.

    Here's a SO post where the OP tried listening for $viewContentLoaded events on the scope (which is yet another alternative), in order to apply some jQuery functions. The suggestion/answer was again to use a directive.

提交回复
热议问题