Angular 1.5动态添加组件

时间:2017-02-26 12:23:09

标签: javascript angularjs angular-components

我有一个简单的APP,我有一个组件,可以从参数中获取数据。

我想在用户点击按钮时多次添加此组件,目前我有这个:

<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>

和我的.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
});

我尝试使用和不使用$ compile但是我仍然无法在页面加载后创建组件,第一个组件加载正常。

我期望的是,点击按钮的新组件带有文字:&#34;嘿我是一个组件&#34;出现,但相反,我得到的只是字面意思

<my-component></my-component>

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

1 个答案:

答案 0 :(得分:4)

你是在思考。只需将.dataTables_wrapper { position: relative; clear: both; zoom: 1; } .dataTables_wrapper:after { visibility: hidden; display: block; content: ""; clear: both; height: 0; } TestsToExecTable { position: relative; table-layout: fixed; float: left; overflow: hidden; } .dataTables_wrapper .dataTables_paginate { float: none; right: 4px; padding: 0px; } .pagination { display: inline-block; padding-left: 0; margin: 3px; margin-bottom: 15px; border-radius: 4px; } 放在ngRepeat上:

myComponent

在JS中也许是这样的事情:

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