【问题标题】:how to put controller in external html file angularjs如何将控制器放入外部html文件angularjs
【发布时间】:2013-10-27 20:55:17
【问题描述】:

我是 AngularJS 的新手。

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

index.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 文件中,但我在控制器中定义的功能不起作用。

有什么想法吗? 如果我不清楚,请告诉我。谢谢。

【问题讨论】:

    标签: javascript html angularjs iframe


    【解决方案1】:

    如果您正在加载 iframe,那么内容将不了解任何有关 Angular 的信息,因此控制器将无法在外部 HTML 中运行。

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

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

    <!-- 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>
    

    【讨论】:

    • 同意 ng-include 是要走的路。当你有一个 iframe 时,它​​有自己的上下文,并且似乎没有从包装页面继承任何东西(CSS 等,我在 facebook 插件上对此进行了斗争,有些事情可以用类来完成,但没有什么可以应用基于我可以告诉我的 iframe 上下文...可能是一个 javascript 解决方法,但不值得)。
    • 感谢您的回答!我以这些方式尝试了您的解决方案: 像这样: 但它不起作用......我做错了什么?
    • 如果您有ng-include,则无需使用iframe。它既可以像iframe 元素的替代品一样工作,也可以像src 属性一样工作,您可以将其放在其他元素(通常是div)上,但我不确定它是否适用于iframe。我很快会在我的答案中添加一个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多