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);
};
EVENT BINDING : The flow of information from elements in a component to the corresponding component's class is event binding (HTML Template to TS) . Event binding works without having to define a template reference variable. This is the best and the easiest method to manipulate DOM elements.
AngularJS has directives for binding application data to the attributes of HTML DOM elements.
DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.
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
If you just need to append certain data on button click, you could have a array on scope which is changed on button click.Bind this model to the view.
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div id="mainDiv">
<p ng-repeat="el in elements">{{el}}</p>
</div>
<button ng-click="appendSomeElement1ToMainDiv()">b1</button>
<button ng-click="appendSomeElement2ToMainDiv()">b2</button>
<button ng-click="appendSomeElement3ToMainDiv()">b3</button>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.elements = [];
$scope.appendSomeElement1ToMainDiv = function() {
$scope.elements.push('el1');
}
$scope.appendSomeElement2ToMainDiv = function() {
$scope.elements.push('el2');
}
$scope.appendSomeElement3ToMainDiv = function() {
$scope.elements.push('el3');
}
});
Working fiddle http://jsfiddle.net/q3Cgj/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With