【问题标题】:How to dynamically add components in AngularJS?如何在AngularJS中动态添加组件?
【发布时间】:2018-08-20 10:09:21
【问题描述】:

请告诉我,如何在控制器中创建组件?

我有带控制器的 angularjs 模块

let app = angular.module('testApp', []);

我尝试加载组件但它没有加载。

app.controller('MainCtrl', ["$scope", function($scope) {
  // I have an array with objects.
  let arr = [{name: 'firstComponent', component: {
      template: "<div>tech filter component</div>",
      controller: [() => {
        let $ctrl = this;
      }]
  }}];
  angular.forEach(arr, (itemArr) => {
    // Why it doesn't init from here ?
    app.component(itemArr.name, itemArr.component)
  });
}]);

这是我的html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>angularjs component</title>
</head>
<body ng-app="testApp" >
<div ng-controller="MainCtrl">
  <first-component></first-component>
</div>
</body>
</html>

jsfiddle link

【问题讨论】:

    标签: javascript angularjs components directive


    【解决方案1】:

    我真的不建议以你尝试的方式动态添加组件。基于对象数组生成组件没有任何好处。但是..如果你真的想这样做,你应该检查你的组件配置对象并删除你的控制器声明附近的[]。另请注意,并非所有支持 AngularJS 的浏览器都支持箭头函数。

    注意: angular bootstrap 被调用后,您无法加载组件。

    查看

    <first-component></first-component>
    

    AngularJS 应用程序

    var myApp = angular.module('myApp',[]);
    
    let myStupidComponentArray =  [{
      name: 'firstComponent', 
      component: {
      template: "<div>tech filter component</div>",
      controller: function () {
        let $ctrl = this;
      }
    }}];
    
    
    angular.forEach(myStupidComponentArray, function (item) {
      myApp.component(item.name, item.component);
    });
    

    > demo fiddle.


    我宁愿不使用循环来创建您的组件。您应该按照定义使用经典方式来做到这一点。它会给你更多的“性能”和更少的代码:

    查看

    <first-component></first-component>
    

    AngularJS 应用程序

    var myApp = angular.module('myApp', []);
    
    myApp.component('firstComponent', {
      template: "<div>tech filter component</div>",
      controller: function() {
        let $ctrl = this;
      }
    });
    

    demo fiddle

    【讨论】:

    • 我写了一个小库,我需要动态加载组件,谢谢,我会检查一下
    • 是的,它可以工作,但我想从控制器加载组件。
    • angular bootstrap 被调用后无法加载组件。
    • @tetramaster 很高兴为您提供帮助。我推了你一点。如果您同意我的方法,请不要忘记标记正确答案。谢谢!
    猜你喜欢
    • 2018-05-13
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2018-02-23
    相关资源
    最近更新 更多