javascript - Angular : ng-include, jQuery 无法工作,除非在 HTML 文件中

标签 javascript jquery html angularjs

我有一个 ng-include html 文件。当我尝试在 js 文件中使用 jquery 时,它不适用于该 html 文件。当我将脚本包含在 HTML 文件中时,它仍然可以工作。我想知道为什么以及如何使 js 文件中的脚本应用于我的 ng-include HTML 文件。

普朗克: https://plnkr.co/edit/eL3e7vLQqaA0NAMKXBSy?p=preview

警告.html:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script>
      $(function(){
        $(".close").css("background","blue");
        $(".close").click(function(){
          $(".box").fadeOut(500);
        });
      });
      </script>
<div class="box">
  <h2>Hey</h2>
  <div class="close">Close</div>
</div>

index.html:

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
      <script src="script.js"></script>
    <script src="jquery.js"></script>
  </head>

  <body ng-app="myApp" ng-controller="myCtrl">
    <div ng-include="'warning.html'"></div>
    <h1>Hello Plunker!</h1>
  </body>

</html>

脚本.js:

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});

jquery.js

$(function(){
$(".close").css("opacity","0");
  $(".close").css("background","blue");
});

最佳答案

ng-include 动态创建 DOM,因此在加载时,您的 jquery 代码已经被执行。一旦 Angular 完成为 warning.html 创建 DOM,您需要执行 jquery 文件内的代码

这是执行此操作的简单方法。 'includeContentLoaded' 在 Angular 加载内容后发出,因此我们可以在其中包含脚本。

app.controller("myCtrl", function($scope, $rootScope,$timeout) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $rootScope.$on('$includeContentLoaded', function() {
    $timeout(function(){
         load();
    });
  });

});

你的 jquery.js 看起来像这样

var load = function() {
  $(".close").css("opacity", "0");
  $(".close").css("background", "blue");
  $(".close").click(function() {
    $(".box").fadeOut(500);
  })

}
load();

现在,您可以从 warning.html 中删除所有脚本

这是 fork

SRC:https://stackoverflow.com/a/22861887/5395350

关于javascript - Angular : ng-include, jQuery 无法工作,除非在 HTML 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960717/

相关文章:

javascript - 在 onkeypress 上获取表的行索引

javascript - 如何将一串数字转换为数字数组?

javascript - 在未来的 CSS 版本中仅在一个方向上固定位置?

javascript - 如何从 "post-46"之类的 id 返回数字

javascript - 滚动期间的不正确行为,根据代码的链接方式显示

html - 嵌入式 DIV 元素的水平定位

javascript - 将 csv 数据加载到 HTML div 中

javascript - 如何从 API 访问数据?

javascript - Android 将 JavaScript 代码绑定(bind)到 Android 代码不起作用?

javascript - 获取同一类的所有元素并通过 jquery 检测其中的第一个元素