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

user3871566
  • 51
  • 1
  • 2
  • 6

3 Answers3

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.

Community
  • 1
  • 1
drew_w
  • 10,320
  • 4
  • 28
  • 49
  • 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. –  Jul 28 '14 at 14:34
  • @KasperLewau Yup, you are correct! I sometimes bind to root scope just for that reason. – drew_w Jul 28 '14 at 15:06
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'
      });
  }]
);
dirkk
  • 6,160
  • 5
  • 33
  • 51
Subash
  • 31
  • 2
  • 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! – dirkk Aug 04 '14 at 10:11
-2

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

thomasnu
  • 88
  • 2