Gonzalo Hernandez
Gonzalo Hernandez

Reputation: 737

Angular 1.5 add component dynamically

I have a simple APP where I have a component that gives me data from a parameter.

I want to add this component multiple times when an user clicks on a button, currently I have this:

<div ng-app="myApp" ng-controller="myCtrl"> 

  <my-component></my-component>
  <br />
  <input type="button" ng-click="addComponent()" value="Add New Component"> 

  <div ng-repeat="c in components">
    {{c.content}}
  </div>
</div>

and my .js

angular.module("myApp", []).controller("myCtrl", function ($scope,$compile) {
    $scope.components = [];

    $scope.addComponent = function(){
        $scope.components.push({content: $compile('<my-component></my-component>')});
    }

});

function componentCtrl($scope) {
    this.text = "Hey I'm a component";

}

angular.module("myApp").component('myComponent', {
  template: '<span>{{$ctrl.text}}</span>',
  controller: componentCtrl
});

I tried both with and without $compile but I still can't create the component after the page has loaded, the first component loads fine.

What I expect is that when clicking the button new components with the text: "Hey I'm a component" appear, but instead I get either nothing or literally

<my-component></my-component>

plunker: https://plnkr.co/edit/IQe8ln?p=preview

Upvotes: 1

Views: 1587

Answers (1)

dfsq
dfsq

Reputation: 193311

You are overthinking. Just put ngRepeat on myComponent:

<my-component ng-repeat="c in components" text="c.text"></my-component>

And maybe something like this in JS:

angular.module("myApp", [])
.controller("myCtrl", function ($scope,$compile) {
    $scope.components = [];

    $scope.addComponent = function(text) {
        $scope.components.push({text: text});
    }
});

function componentCtrl($scope) {
  // something here
}

angular.module("myApp").component('myComponent', {
  template: '<span>{{$ctrl.text}}</span>',
  controller: componentCtrl,
  bindings: {
    text: '='
  }
});

Upvotes: 4

Related Questions