2017-02-26 82 views
1

我有一个简单的应用程序,其中有一个组件,它提供了来自参数的数据。Angular 1.5动态添加组件

我想这个组件多次当用户点击添加按钮上,目前我有这样的:

<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 
}); 

我既没有$尝试编译但我仍然无法在页面加载后创建组件,第一个组件加载正常。

我希望那是什么点击按钮与文字的新组件时:“嘿,我的组件”的出现,而是我得到存在或是字面上

<my-component></my-component> 

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

回答

3

你正在过度使用。只要把ngRepeatmyComponent

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

也许这样的事情在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: '=' 
    } 
}); 
+0

你是对的,有时候我得深,棱角分明。谢谢! –