Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript code after angularjs route loaded

I need to show an alert after a route has been loaded by angularjs. The piece of code to show the alert is in the view loaded asynchronously by angularjs:

<script>
alert('test');
</script>

Once the view has loaded, I expect this to be run, but it does not. I know I can broadcast and tell it to run afterwards etc, but I need a more generic solution.

like image 672
user3428172 Avatar asked Apr 16 '14 02:04

user3428172


2 Answers

There is one more option to run javascript function use ngInit

<div ng-init="initialize()"></div>

call the function which is inside the controller

app.controller('myController', function($scope){
    $scope.initialize = function () {
        alert("Page loading just completed");
    }
});
like image 43
Mo. Avatar answered Oct 26 '22 23:10

Mo.


Assuming you are talking about route changes based upon ngRoute internal to an angular SPA

Inject $route into your controller:

.controller('MyCtrl', function($scope, $route){});

and in your controller you subscribe to the event of the route changing:

$scope.$on('$routeChangeSuccess', function() {
    alert('test'); // <-- alert from the question
});
like image 152
Brocco Avatar answered Oct 27 '22 00:10

Brocco