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