3

I have used ng-init="isauthorised()" in my code to get call function after changing every URL

it call when page get refresh but I need this function to get call afer every click on ancher tag

1
  • Could you please post the code for isauthorised()? Commented Jul 24, 2014 at 13:51

3 Answers 3

6

One of the best things to do is to use the route provider to call a function before the page change happens. One example of this (modified from here) is:

$scope.$on('$locationChangeStart', function(event) {
    // call your method here
});

The nice thing about this is you know your routine is going to get called and you don't have to modify the code for every anchor tag on the page. By the way, if you are interested in more information check the angular documentation here.

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

2 Comments

I'd be sure to mention that this $on listener needs to be present in every pageview pertaining to a location change. An alternative would be to set the listener on $rootScope, but then you need to manually unbind it when you are done with the listener. So, saying that it will happen on every $locationchangestart, is only partly true. The listener needs to be alive for the callback to run.
@KasperLewau Yup, you are correct! I sometimes bind to root scope just for that reason.
3

In your application if you want to trigger the function whenever the route changes,Below codes will use

$scope.$on('$routeChangeStart', function(next, current) { 
   ... This Function will trigger when route changes ...
 });

$scope.$on('$routeChangeSuccess', function(next, current) { 
   ... This Function will trigger After the route is successfully changed ...
 });

if you want to trigger the function, for particular routes, you give it in resolve functions in app.config

for example

myapp.config(['$routeProvider',
  function($routeProvider) {

    $routeProvider.
      when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
      }).
      when('/home', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl',
        resolve: {
          token: function(Token){
            ... Trigger the function what u want, and give token as dependency for particular route controller ...
          }
        }
      }).

      otherwise({
        redirectTo: 'index.html'
      });
  }]
);

1 Comment

Please take care to use proper code formatting, I edited your post for you. Even more important, please do not use "u" instead of "you" - It makes me want to stab my eyes out!
-2

Add ng-click="isauthorised()" or do you mean something else?

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.