How can I append some angular elements to a div without doing dom manipulations in the controller?

angularjs

Solution

Directives are what you are looking for. You can do something like this:

myApp.directive('mainArea', function() {
    return {
        restrict: "E",
        template: "<div>"+
            "<div id='mainDiv'> </div>" +
            "<button data-ng-click='append()'>Add</button>" +
        "</div>",
        controller: function($scope, $element, $attrs) {
            $scope.append = function() {
                var p = angular.element("<p />");
                p.text("Appended");
                $element.find("div").append(p);
            }
        }
    }
});

And in your HMTL:

<main-area></main-area>

Working Fiddle

If your element is a directive, you should take a look at `$compile`

Problem

There is a div with some id say mainDiv. And then there are three buttons. Clicking on each button appends a different angular element with different directives to the mainDiv. ``` <div id="mainDiv"></div> <button ng-click="appendSomeElement1ToMainDiv()"></button> <button ng-click="appendSomeElement2ToMainDiv()"></button> <button ng-click="appendSomeElement3ToMainDiv()"></button> ``` How can I achieve this without using dom manipulations in controller. Its too tempting to use ``` $scope.appendSomeElement1ToMainDiv = function () { var element1 = angular.element("<p>I am a new element</p>"); $("#mainDiv").append(element1); }; ```

Original source