user5778346
user5778346

Reputation:

Load javascript when page load in angularjs

I try this method , but it is not working for me , I am beginner in AngulartJS

var getDb = angular.module('dataapp', [])
  .controller('datagetcontroller', function ($scope,$window) {
    $window.onload = function(){
      alert('this is test')
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<tr ng-app="dataapp" ng-controller="datagetcontroller"><td>loremipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td></tr>

Thank in advance.

--UPDATE-- Maybe I have problem , because before new page load I use page redirect via

window.location.href

, which help I redirect to page where I need to execute javascript.

Upvotes: 1

Views: 2663

Answers (3)

user5778346
user5778346

Reputation:

This was my solution

angular.element(window).bind('load', function() {
    
});
Other reason that my angular did not work , was in a simple mistake , I do not have right to use more than one ng-app="" inside one html file

Upvotes: 0

Arun kumar
Arun kumar

Reputation: 1625

    var getDb = angular.module('dataapp', [])
    .controller('datagetcontroller', function ($scope) {
    //assign to scope function
    $scope.load = function() {
           alert("Window is loaded");
     }}});



 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
//call load function in ng-init
<tr ng-app="dataapp" ng-controller="datagetcontroller" ng-init="load()"><td>loremipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td><td>Lorem ipsum</td></tr>

Upvotes: 2

JEET ADHIKARI
JEET ADHIKARI

Reputation: 539

I have also added a working plunkr https://plnkr.co/edit/DD0BeZLqZbZcoxCDNi1g?p=preview. Suppose your .js file is script.js which looks like:

var getDb = angular.module('dataapp', [])
.controller('datagetcontroller', function ($scope,$window) { $window.onload = function(){ alert('this is test') } });

and your html page is index.html where head should look like have: <head> <link rel="stylesheet" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="dataapp"> <table> <tr ng-controller="datagetcontroller"> <td>loremipsum</td> <td>Lorem ipsum</td> </tr> </table> </body>

It should work fine. I think you have not declared the script.js file in the index.html where you have written the javascript. Also note that, you have to place the angular.min.js script above the script.js as angular needs to load before hand so that script.js understands the code.

Upvotes: 1

Related Questions