【问题标题】:how to append a html template to a div/directive on click with angular js?如何在点击 Angular js 时将 html 模板附加到 div/指令?
【发布时间】:2013-03-14 06:39:20
【问题描述】:

我有这种情况:

<somebutton></somebutton>

...

app.directive("somebutton", function(){
    return {
        restrict: "E",

        scope: {
          // not sure what i can do here
        },

        template: '<button ng-click="loadTemplate()" type="button">Text</button>',

        link: function(scope, element){
            scope.loadTemplate = function(){

                //TODO: append "home.html" template inside body directive
            }
        }
    }
});

...

<script type="text/ng-template" id="home.html">
    <div>home</div>
</script>

...

<div body ></div>

这样做的其他方法可能是将按钮放在 html 中而不是模板中

<button ng-click="loadTemplate()" type="button">Text</button>

然后可能有一个控制器,它具有加载模板的 loadTemplate() 方法

但我不确定如何做到这一点。

令人困惑?是的:)

对这个问题有什么想法吗?

谢谢

【问题讨论】:

  • 我最近开始使用 Angular 并确保正确地做事让我感到困惑......考虑像 Angular HTML 被视为模板,因此不确定使用其他带有 Angular 的模板工具......期待一些答案...

标签: javascript html templates button angularjs


【解决方案1】:

看看ngInclude,如果它符合您的需求。您可以将其绑定到模板 url 以动态更改加载的模板。

查看the documentation 的示例以及此simple plnkr

<body>
  <button ng-click="template='home.html'">Home</button>
  <button ng-click="template='home2.html'">Home 2</button>
  <div ng-include src="template"></div>
</body>
<script type="text/ng-template" id="home.html">
    <div>loaded home</div>
</script>
  <script type="text/ng-template" id="home2.html">
    <div>loaded home 2</div>
</script>

另请注意,大​​多数 AngularJS 应用程序可能使用内置路由来根据 url 加载适当的控制器和视图。有关详细信息,请参阅 the tutorial$route 上的文档/示例。

【讨论】:

  • 这样就可以切换模板了。我正在寻找将模板加载/附加到 div/指令。我的问题可能会让人们有点失望
  • 啊,在这种情况下,$compile 文档可能会有所帮助。
  • 对我来说什么都没发生
猜你喜欢
  • 2015-09-07
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多