[英]Angular: ng-include, jQuery not working unless in HTML file
I have aa ng-include
html file. 我有
ng-include
html文件。 When I try to use jquery
in my js file, it doesn't apply to that html file. 当我尝试在我的js文件中使用
jquery
时,它不适用于该html文件。 When I include the script in the HTML file it works though. 当我在HTML文件中包含脚本时,它可以工作。 I was wondering why and how I can make my scripts in my js file apply to my
ng-include
HTML file. 我想知道为什么以及如何使我的js文件中的脚本适用于我的
ng-include
HTML文件。
Plunkr: https://plnkr.co/edit/eL3e7vLQqaA0NAMKXBSy?p=preview Plunkr: https ://plnkr.co/edit/eL3e7vLQqaA0NAMKXBSy ? p = preview
Warning.html: 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: 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: 的script.js:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
jquery.js 的jquery.js
$(function(){
$(".close").css("opacity","0");
$(".close").css("background","blue");
});
ng-include creates the DOM dynamically, so by the time its loaded, your jquery code has already been executed. ng-include动态创建DOM,因此在加载时,您的jquery代码已经被执行。 You need to execute the code inside the jquery file once angular has finished creating the DOM for warning.html
一旦angular完成为warning.html创建DOM,您需要在jquery文件中执行代码
Here is a simle way of doing this. 这是一种类似的方式。 'includeContentLoaded' is emitted after angular loads content, so we can include scripts inside that.
'includeContentLoaded'是在角度加载内容后发出的,因此我们可以在其中包含脚本。
app.controller("myCtrl", function($scope, $rootScope,$timeout) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$rootScope.$on('$includeContentLoaded', function() {
$timeout(function(){
load();
});
});
});
Your jquery.js would look something like this 你的jquery.js看起来像这样
var load = function() {
$(".close").css("opacity", "0");
$(".close").css("background", "blue");
$(".close").click(function() {
$(".box").fadeOut(500);
})
}
load();
Now, you can remove all the scripts from warning.html 现在,您可以从warning.html中删除所有脚本
SRC: https://stackoverflow.com/a/22861887/5395350 SRC: https : //stackoverflow.com/a/22861887/5395350
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.