8

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.

1

2 Answers 2

22

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

how can I do this on a specific route?
@AhmedNassar this is possible, but a separate question should be created so that others that have that issue can find it and find it useful. You can post a link to your question here and I will take a look at it then.
5

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

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.