1

I've made an app with 3 slightly different views which use the same logic, so each one uses the same controller, but have different json data. Everything is working fine, but I was wondering if it is AngularJS best practice to do so ? When routes change, does the view replaced uses the same instance of the controller, or does it instantiate a new controller ?

Thanx.

2
  • In my small experience, each time a view changes, its controller was reloaded. I'm using ui-router, so maybe AngularJs basic routes don't have the same behavior. You can put "console.log" in your controller to detect this. Commented Dec 10, 2013 at 15:55
  • I wondered the same about here is some helpful info Angular Best Practices Commented May 17, 2014 at 22:43

1 Answer 1

1

A new controller is created each time a view is loaded--controllers are transient in this sense. If state needs to be maintained, you should use a service or factory.

I personally will share controllers between different variations of the same view. In a general sense, if the controller represents the same logic (or abstraction) in relation to the view, I see no reason not to re-use it.

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

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.