2016-08-15 104 views
1

我有一個ng-include html文件。當我嘗試在我的js文件中使用jquery時,它不適用於該html文件。當我將腳本包含在HTML文件中時,它可以工作。我想知道爲什麼以及如何讓我的js文件中的腳本適用於我的ng-includeHTML文件。Angular:ng-include,jQuery不能工作,除非在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"); 
}); 

回答

0

ng-include動態創建DOM,所以在加載時,您的jquery代碼已經被執行。您需要在角度完成創建DOM後執行jquery文件中的代碼warning.html

下面是這樣做的一個簡單方法。 'includeContentLoaded'是在角度加載內容之後發出的,因此我們可以在其中包含腳本。

你的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