如何将已启用Angular的元素添加到DOM

如何将已启用Angular的元素添加到DOM

本文介绍了如何将已启用Angular的元素添加到DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式添加一些支持Angular的DOM元素。实际上,我可能需要添加自定义组件。我怎么能这样做?

I would like to add some Angular-enabled DOM elements programmatically. Actually, I probably will need to add custom components. How can I do it?

这是一个简单的小提琴来演示这个问题:

Here's a trivial fiddle to demonstrate the issue: http://jsfiddle.net/ZJSz4/2/

HTML:

<div ng-app="main">
    <div ng-controller="MyCtrl">
        <button ng-click="add()" >Add</button>
        <div id="container">
            <div>{{test}}</div>
        </div>
    </div>
</div>

JS:

angular.module("main", []).controller("MyCtrl", function($scope) {
    $scope.add = function() {
        $("#container").append("<div>{{test}}</div>");
    };

    $scope.test = 'Test Message';
});

为了以防万一,我希望它为每次点击添加一个显示测试消息的div - 而不是{{test}}。

Just in case, I expect it to add a div showing "Test Message" for each click - not {{test}}.

为什么需要它?好吧,我希望有一些可排序的列(在jQuery可排序的意义上)与portlet。我想每个portlet都可以成为一个组件。

Why do I need it? Well, I would like to have a few sortable columns (in jQuery sortable sense) with portlets. I imagine each portlet could be a component.

我爬错了山吗?什么是Angular解决这个问题的方法?

Am I climbing the wrong hill? What is the Angular way to solve this?

EDIT :我希望这个简单的例子不会以这种方式结束,但无论如何。最终目标不是为数组中的每个元素显示div。

EDIT: I hoped this simplistic example wouldn't end that way, but anyway. The ultimate goal is not to display a div for each element in an array.

我真正想要的是一个更复杂的控制器。我需要一个有一些有趣行为的portlet容器。可能需要决定将每个portlet放在不同的列中。它可能会提供更改布局,并在这种情况下有一个很好的方式来重新组织portlet。等等。

What I really want is a more complex controller. I need a portlet container with some interesting behavior. It may need to decide to place each portlet in a different column. It may offer changing the layout and have a decent way to reorganize portlets in such event. And so on.

推荐答案

虽然我不完全确定所需的结果是什么,但您确实希望确保所有DOM操作是在一个指令内完成的,而不是在你的控制器里面。

Although I am not entirely sure what the desired outcome is, you do want to be sure that all DOM manipulation is done within a directive and not inside your controller.

这个JSfiddle例子应该让你朝着正确的方向前进。

This JSfiddle example should get you going in the right direction.

<div ng-app="main">
<div ng-controller="MyCtrl">
<div id="container">
    <button ng-click="add()" >Add</button>
    <ng-portlet></ng-portlet>
</div>
</div>
angular.module("main", []).controller("MyCtrl", function($scope) {
    $scope.test = 'Test Message';
}).directive("ngPortlet", function ($compile) {
return {
    template: '<div>{{test}}</div>   ',
    restrict: 'E',
    link: function (scope, elm) {
        scope.add = function(){
            console.log(elm);
           elm.after($compile('<ng-portlet></ng-portlet>')(scope));
        }
    }
};
});

这篇关于如何将已启用Angular的元素添加到DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:10