处理 AngularJS 中的 DOM 操作 [英] Dealing with DOM Manipulations in AngularJS

查看:24
本文介绍了处理 AngularJS 中的 DOM 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 jQuery 执行 DOM 操作(添加新 HTML)时,AngularJS 不会自动检测新 HTML 中的变量并将它们替换为它们的值.例如:

$scope.showSummary = function($event){$($event.currentTarget).html("

{{row}}

");};

这是一个简单的例子,但是改变了元素中的HTML(这个函数被ng-click调用)后,输出还是{{row}} 而不是 row 在上下文/范围中的含义.

解决方案

你必须注入 $compile (http://docs.angularjs.org/api/ng.$compile) 并使用它,以便 angular 了解新的 html.

$compile('<div>{{row}}</div')($scope).appendTo($event.currentTarget);

然而,在控制器中进行 DOM 操作在角度上是不受欢迎的.您希望您的控制器处理业务,而您的视图处理视图.

尝试一个指令来做你想做的事.http://docs.angularjs.org/guide/directive

When I perform DOM manipulation (add new HTML) using jQuery, AngularJS doesn't automatically detect variables in the new HTML and replace them with their values. For example:

$scope.showSummary = function($event){

    $($event.currentTarget).html("<div>{{row}}</div>");

};

This is a simple example, but after changing the HTML in the element (this function was called by ng-click), the output it still {{row}} instead of what row should mean in the context/scope.

解决方案

You have to inject $compile (http://docs.angularjs.org/api/ng.$compile) and use it so angular knows about the new html.

$compile('<div>{{row}}</div')($scope).appendTo($event.currentTarget);

However, it is frowned upon in angular to do DOM manipulation in your controllers. You want your controllers to handle business and your views to handle the view.

Try a directive to do what you want. http://docs.angularjs.org/guide/directive

这篇关于处理 AngularJS 中的 DOM 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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