角度动态元素与模板和控制器

时间:2017-02-06 13:47:45

标签: javascript angularjs dynamic

使用模板文件和某个控制器点击我的HTML后,我无法理解如何添加动态内容。

我想要像:

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

Angular 1.5.8

2 个答案:

答案 0 :(得分: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);
        });
      }
    };})
    

答案 1 :(得分:0)

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