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");
});

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.