【问题标题】:Angular dynamic element with template and controller带有模板和控制器的角动态元素
【发布时间】:2017-06-23 11:42:29
【问题描述】:

我不明白如何在点击带有模板文件和一些控制器的 HTML 后添加动态内容。

我想要类似的东西:

element.click(function(){
  element2.html(templateUrl, controller);
});

Angular 1.5.8

【问题讨论】:

  • 我建议你先阅读this。然后,关于您的问题,最好使用ngRoute 模块:请参阅此example

标签: javascript angularjs dynamic


【解决方案1】:

虽然问题不是很清楚,但我觉得您想要做的是动态呈现 html。有两种解决方案:

  1. angular-routing:这主要用于如果你想导航到应用程序中的不同页面,但你也希望应用程序是一个 SPA(单页应用程序),没有页面重新加载,你可以使用ngRoute 模块。这方面的内容随处可见。你可以看看他们。
  2. custom-directive:您可以尝试编写一个指令,该指令将在您想要的任何事件上呈现 html:

    .directive("customTemplateLoad", function($http, $templateCache, $compile) {
    return {
      restrict: 'A',
      link: function(scope, element, attr, controller){
        var template;
        // Some logic to get template, perhaps pass it in the directive itself
        var templatePath = '/templates/'+template;
        $http.get(templatePath, { cache: $templateCache }).success(function(response) {
          var contents = element.html(response).contents();
          $compile(contents)(scope);
        });
      }
    };})
    

【讨论】:

  • 我已经有带有角度路由的 SPA 应用程序。我对模型警报有一些看法,我想在所有警报之后添加警报创建表单。
  • 也许像做 document.write 这样的事情可能会有所帮助。您可能会发现这 (stackoverflow.com/questions/19637312/…) 很有帮助。如果您准备好一个文档 html,它会为您插入该 html,这样做有帮助吗?
【解决方案2】:

您可以使用控制器和模板创建指令,编译它然后将其添加到 DOM。

【讨论】:

    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多