[英]Angular 1.5 add component dynamically
我有一个简单的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和不使用$ compile,但是在页面加载后仍然无法创建组件,第一个组件可以正常加载。
我期望的是,单击按钮后出现带有以下内容的新组件:“嘿,我是一个组件”,但是我什么也没得到,
<my-component></my-component>
你太想了。 只需将ngRepeat
放在myComponent
:
<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: '='
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.