1

I have a a ng-include html file. When I try to use jquery in my js file, it doesn't apply to that html file. When I include the script in the HTML file it works though. I was wondering why and how I can make my scripts in my js file apply to my ng-include HTML file.

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");
});
Snorlax
  • 4,425
  • 8
  • 37
  • 68

1 Answers1

0

ng-include creates the DOM dynamically, so by the time its loaded, your jquery code has already been executed. You need to execute the code inside the jquery file once angular has finished creating the DOM for warning.html

Here is a simle way of doing this. 'includeContentLoaded' is emitted after angular loads content, so we can include scripts inside that.

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

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

Heres a fork

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

Community
  • 1
  • 1
Kaushal Niraula
  • 563
  • 3
  • 7