本文介绍了AngularJS:在AngularJS渲染模板后如何运行其他代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DOM中有一个Angular模板。当我的控制器从服务器获取新的数据时,它会更新$ scope中的模型,并重新渲染模板。所有的好,迄今为止。



问题是,我还需要做一些额外的工作,在模板被重新渲染之后并且在DOM(在这种情况下是一个jQuery插件)。



似乎应该有一个事件来听,比如AfterRender,但是我找不到这样的东西。也许一个指令会是一种方式,但是似乎也太早了。



这是一个jsFiddle,概述了我的问题:



== UPDATE ==



根据有用的评论,我已经相应地切换到一个指令来处理DOM操作,并在指令中实现了一个模型$ watch。但是,我仍然有同样的基础问题; $ watch事件之前的代码在模板被编译并插入DOM之前被触发,因此,jQuery插件总是在评估一个空的表。



有趣的是,如果我删除异步调用,整个事情都可以正常工作,所以这是一个正确的方向。



这是我更新的小提琴来反映这些变化:

解决方案

这篇文章是旧的,但是我将您的代码更改为:

  watch(assignment,function(value){//我在这里更改
var val = value || null;
if(val)
element.dataTable({bDestroy });
});
}

看到:



我希望它能帮助你


I have an Angular template in the DOM. When my controller gets new data from a service, it updates the model in the $scope, and re-renders the template. All good so far.

The issue is that I need to also do some extra work after the template has been re-rendered and is in the DOM (in this case a jQuery plugin).

It seems like there should be an event to listen to, such as AfterRender, but I can't find any such thing. Maybe a directive would be a way to go, but it seemed to fire too early as well.

Here is a jsFiddle outlining my problem: Fiddle-AngularIssue

== UPDATE ==

Based on helpful comments, I've accordingly switched to a directive to handle DOM manipulation, and implemented a model $watch inside the directive. However, I still am having the same base issue; the code inside of the $watch event fires before the template has been compiled and inserted into the DOM, therefore, the jquery plugin is always evaluating an empty table.

Interestingly, if I remove the async call the whole thing works fine, so that's a step in the right direction.

Here is my updated Fiddle to reflect these changes: http://jsfiddle.net/uNREn/12/

解决方案

This post is old, but I change your code to:

scope.$watch("assignments", function (value) {//I change here
  var val = value || null;
  if (val)
    element.dataTable({"bDestroy": true});
  });
}

see:http://jsfiddle.net/dnzY9/

I hope it help you

这篇关于AngularJS:在AngularJS渲染模板后如何运行其他代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:12