0

What I'm trying to do:

Is there any way to use an array of elements to populate a div with children in AngularJS?

I want to be able to have an array of custom elements, and as I update the array, it updates the view. The directives for the custom elements need to $scope.$digest() the elements each time I make an update.


Pseudo Code:

html

<div id="parent" ng-controller="parentCtrl" ng-bind-html="arrOfElems"></div>

Javascript

app.controller('levelCtrl', ['$scope', '$compile', '$element', function(scp, cmpl, elem) {
  scp.arrOfElems = ['<ell></ell>', '<r-ell></r-ell>', '<sqr></sqr>'];
}]);

app.directive('ell', function() {
  return {
    restrict: 'E',
    template: <div class="block"></div>
  };
});
app.directive('rEll', function() {
  return {
    restrict: 'E',
    template: <div class="block"></div>
  };
});
app.directive('sqr', function() {
  return {
    restrict: 'E',
    template: '<div class="block"></div>'
  };
});

Ideally, the resulting html would be:

<div id="parent" ng-controller="parentCtrl" ng-bind-html="arrOfElems">
  <ell>
    <div class="block"></div>
  </ell>
  <r-ell>
    <div class="block"></div>
  </r-ell>
  <sqr>
    <div class="block"></div>
  </sqr>
</div>

1 Answer 1

1

Create a simple loading directive that compiles them and inserts them

<div id="parent" ng-controller="parentCtrl" my-loader="arrOfElems"></div>

Untested but should work:

app.directive('myLoader',function($compile){
   return function(scope, elem, attrs){
        var arrOfElems=scope[attrs.myLoader];
        angular.forEach( arrOfElems, function(newEl){
          elem.append( $compile(newEl)(scope) );
        });
   }
});

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

Tested it out, worked perfectly! Initially I thought it would only add the elements when angular bootstraps, but it updates the view as you update the array.
i didn't catch the part about updating array. Might have to add a watch and empty the element when array changes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.