如何在单击按钮时渲染外部模板

How to render external template on button click?

本文关键字:外部 单击 按钮      更新时间:2023-09-26

假设我有以下标记:

<main ng-controller="MainController">
    <article id="story-container"></article>
    <button ng-click="newSection()">+ Add Section</button>
 </main>

我需要在点击按钮时在文章元素中编译并附加以下模板。

<script  id="newSectionTmpl" type="text/ng-template">
    <section>Hello, {{name}}!</section>
</script>

我尝试过这样的方法,但不确定这是否是一个好方法:

app = angular.module('myApp', []);
app
  .controller('MainController',['$scope', '$compile', function($scope, $compile) {
    $scope.name = "Denis";
    $scope.newSection = function() {
      var tmpl = $('#newSectionTmpl').html();
      var $el = $('#story-container');
      console.log(tmpl);
      var html = $compile(tmpl)($scope);
      $el.append(tmpl);
    }
  }                                                                
]);

此外,如何从外部文件加载模板?以下是指向jsBin的链接:http://jsbin.com/zuyicewexahi/5/edit?html,js,输出

Tryng-include指令ng包括文件

<div class="modal-header">
<form  ng-include src="'/src/sample.html'"></form>
</div>

sample.html是一个外部文件,它将使用ng-include指令

加载到当前的html中

Angular非常棒,您不需要大部分jquery。参见下面的plunkr:http://plnkr.co/edit/yqhnQyR4NrFvnUBn7ite?p=preview

您需要将名称设置为"Noypi"只是开玩笑…"

app.controller('MainController',['$scope', function($scope) {
    $scope.name = "Noypi";
    $scope.content = "";
}]);

html。。。

  <div ng-controller="MainController">
    <button ng-click="content = 'newSectionTmpl'">+ Add Section</button>
    <div  ng-include src="content"></div>
  </div>