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 fiddl
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.
This JSfiddle example should get you going in the right direction.
http://jsfiddle.net/ZJSz4/5/
<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));
}
}
};
});
If you want multiple tests, I'd suggest setting it up like so.
<div ng-app="main">
<div ng-controller="MyCtrl">
<button ng-click="add()" >Add</button>
<div id="container">
<div ng-repeat="test in tests">{{test.name}}</div>
</div>
</div>
</div>
$scope.tests = []; // define this as an array
$scope.add = function() {
var newTest = {name: 'Test Message'};
$scope.tests.push(newTest);
};
This will dynamically create divs based on your tests object.
As @Christopher Marshall pointed out, the simplest way to do this is using a repeating element and pushing a new item into scope on the button press.
[HTML]
<div ng-app="main">
<div ng-controller="MyCtrl">
<button ng-click="add()" >Add</button>
<div id="container">
<div ng-repeat="test in tests">{{test}}</div>
</div>
</div>
</div>
[JS]
angular.module("main", []).controller("MyCtrl", function($scope) {
$scope.add = function() {
$scope.tests.push('New Message');
};
$scope.tests = ["Test Message","Test Message 2"];
});