0

I have a situation where a button is provided for the user to click. After clicking the button, a new <div> (which is actually a template with isolated scope) is created, and this <div> is appended to the existing element, like so:

<button ng-click="openNewDiv()"></button>
<div>Div content for DIV 1</div>
<div>Div content for DIV 2</div>
<div>Div content for DIV 3</div>
<div>Div content for DIV 4</div>

Each <div> shares the same template and logic, with isolated scope, when user clicks the button, a fifth <div> is appended next to DIV4, which also shares the same logic as the above 4 <div>'s, how can I achieve this in AngularJS? I am reading this article to find the solution, am I on the right direction?

http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

Bond
  • 16,071
  • 6
  • 30
  • 53
user2499325
  • 419
  • 1
  • 5
  • 15

1 Answers1

1

This is can achieved using directives, see here for the docs. You can make a directive which contains the template and logic for the <div> elements. As for adding this directive multiple times when a button is clicked you can use an ngRepeat to iterate over an array containing the directive data.

In your controller:

$scope.myData = [dataDiv1, dataDiv2, ..., dataDivx];
$scope.openNewDiv = function() {
    $scope.myData.push(anotherDataDiv);
};

In your view:

<button ng-click="openNewDiv()"></button>
<my-directive myData="data" ng-repeat="data in myData"></my-directive>
Miles P
  • 710
  • 4
  • 12
  • Thanks very much for the clarification, I am wondering if $compile service is suitable in my case, so in this case $compile is not necessary? – user2499325 Aug 06 '15 at 02:48
  • I would use the `link` function instead of the `compile` function for your directive. [See this post for more info](http://stackoverflow.com/questions/15676614/directive-link-vs-compile-vs-controller) – Miles P Aug 06 '15 at 02:51
  • I am curious when should I use $compile, as from my search, $compile is to compile the newly made DOM to the existing one, which is somehow match my case – user2499325 Aug 06 '15 at 02:54
  • 1
    The biggest difference between `link` and `compile` is that `compile` only gets called once, irregardless if multiple copies are made of the directive (in our case by ng-repeat). – Miles P Aug 06 '15 at 03:00