Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I previously thought that the controller script would only be executed once, when my single page application is loaded.

Now I see that every time I change a view my controller script executes again. I can tell because i had a couple of statements in the script that are not nested in functions. I want them to happen only when the app is first loaded, but they are running when I change views.

The views are configured in my app.js with module.config:

  myModule.config(function ($routeProvider) {
    $routeProvider
      .when('/search', {
        templateUrl: 'views/search.html',
        controller: 'searchCtrl'
      })
      .when...

So, is it normal for the controller script to run when the view changes? Or should I be searching for something I have configured wrong?

share|improve this question
    
I should have mentioned that the other views also use the searchCtrl controller. –  Michael Stack May 14 at 1:36
add comment

1 Answer

Yes this is normal. It was(/is) the same for me, however I use angular-ui-router... The solution I chose in order to make sure that the data in the controller would persist was to use a factory, you could use a service or provider just as well.

"Specialized objects conform to a specific Angular framework API. These objects are one    
 of controllers, directives, filters or animations.

 The injector needs to know how to create these objects. You tell it by registering a 
 "recipe" for creating your object with the injector. There are five recipe types.

 The most verbose, but also the most comprehensive one is a Provider recipe. The 
 remaining four recipe types — Value, Factory, Service and Constant — are just 
 syntactic sugar on top of a provider recipe."

https://docs.angularjs.org/guide/providers

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.