Angular: ng-include, jQuery只有在HTML文件中才能工作

Angular: ng-include, jQuery not working unless in HTML file

本文关键字:文件 HTML 工作 ng-include jQuery Angular      更新时间:2023-09-26

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

Plunkr:https://plnkr.co/edit/eL3e7vLQqaA0NAMKXBSy?p=preview

Warning.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>

Script.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,因此在加载DOM时,您的jquery代码已经执行完毕。你需要在angular为warning.html

创建完DOM后执行jquery文件中的代码。

这里有一个简单的方法。' inclecontentloaded '是在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