AngularJS:如何在 AngularJS 呈现模板后运行附加代码? [英] AngularJS: How to run additional code after AngularJS has rendered a template?

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

问题描述

我在 DOM 中有一个 Angular 模板.当我的控制器从服务中获取新数据时,它会更新 $scope 中的模型,并重新呈现模板.到目前为止一切都很好.

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.

问题是,在重新渲染模板并在 DOM 中(在本例中为 jQuery 插件)后,我还需要做一些额外的工作.

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).

好像应该有一个事件可以监听,比如AfterRender,但是我找不到任何这样的东西.也许指令是一种方式,但它似乎也为时过早.

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.

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

Here is a jsFiddle outlining my problem: Fiddle-AngularIssue

== 更新 ==

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

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.

这是我更新的 Fiddle 以反映这些变化:http://jsfiddle.net/uNREn/12/

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});
  });
}

参见 jsfiddle.

希望对你有帮助

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆