Reputation: 7275
I have angular code that creates a div using 'box1' directive. Inside of that box there is a button. When that button is clicked I want it to call another directive that is called 'box2'. This box2 will go inside of box1. How do I do this?
HTML:
<div ng-app="myApp">
<div>
<box1>
</box1>
</div>
</div>
ANGULAR:
var app = angular.module("myApp", []);
app.directive("box1", function () {
return {
restrict: "E",
template: '<div id="group_1">Content from the first box! <button>Create 2nd Box</button></div>'
}
});
app.directive("box2", function () {
return {
restrict: "E",
template: '<div id="group_1_1"> Content from second box! </div>',
}
});
What is the proper way in Angular to make the button in the first box call the box2 directive. Also I can't just write inside of box1 directive template because it will just auto generate box2. I don't want that. I want them to click inside of box1's button to make box2.
Link to JsFiddle if anyone is interested. http://jsfiddle.net/RZSKe/
Upvotes: 0
Views: 48
Reputation: 20348
Not sure if I understood you correctly, but it seems that you should make use of the $compile
service. Here is a seed of what I mean by it - it should be probably tailored to your needs:
var app = angular.module("myApp", []);
app.directive("box1", function ($compile) {
return {
restrict: "E",
template: '<div id="group_1">Content from the first box! <button ng-click="createBox2()">Create 2nd Box</button></div>',
link: function (scope, el) {
scope.createBox2 = function () {
var box2 = $compile("<box2></box2>")(scope);
el.append(box2);
}
}
}
});
app.directive("box2", function () {
return {
restrict: "E",
template: '<div id="group_1_1"> Content from second box! </div>',
}
});
Upvotes: 2