1

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

1 Answer 1

4

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: '='
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

you are right, sometimes I got to deep with angular. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.