如何将控制器放在外部HTML文件中 AngularJS.

how to put controller in external html file angularjs

本文关键字:HTML 文件 AngularJS 外部 控制器      更新时间:2023-09-26

我对AngularJS很陌生。

我有一个带有一些按钮的网络应用程序:

索引.html

<button class="aButton">a</button>  
<button class="bButton">b</button>
 <script>
   $(document).ready(function(){
      $(".aButton").click(function(){
        $(".aField").fadeIn(400);
      });
   });
</script>
<script>
  $(document).ready(function(){
      $(".bButton").click(function(){
        $(".bField").fadeIn(400);
      });
   });
</script>

当我单击不同的按钮时,它们会根据单击的按钮显示 iframe。在这些 iframe 中,我通过 src 放置了一个外部 html 文件。

<iframe class="aField" style="display: none;" src="a.html" width="700" height="1000" ></iframe>
<iframe class="bField" style="display: none;" src="b.html" width="700" height="1000" ></iframe>

直到这里没问题。

问题出在外部 html 文件(a.html 和 b.html)中,每个文件都需要不同的控制器。我尝试将 ng-controller 标签放在 iframe 和外部 html 文件中,但我在控制器中定义的函数不起作用。

知道吗?如果我不清楚,请告诉我。谢谢。

如果你正在加载iframe,那么内容将不知道任何关于角度的信息,所以控制器在外部HTML中不起作用。

您可能需要查看将部分 HTML 文件包含在页面中的ng-include。使用它,HTML将直接插入到您的页面中,并像应用程序的其余部分一样进行编译/链接。

下面是使用 ng-include 的示例。我还用ng-click替换了jQuery点击处理程序,用ng-show替换了.fadeIn s,以使解决方案更有棱角。

<!-- These buttons just set variables on the scope when clicked -->
<button ng-click="showA=true">a</button>  
<button ng-click="showB=true">b</button>
<script>
  // Nothing left here now
  // The contents of ng-click could be moved into a JS controller here...
</script>
<!-- the ng-include attribute value is an angular expression. If you use a string, wrap it in quotes -->
<div ng-include="'a.html'" ng-show="showA" width="700" height="1000"></div>
<div ng-include="'b.html'" ng-show="showB" width="700" height="1000" ></div>