I have a situation where I need to dynamically change the controller, so that the scope variables are influenced accordingly. General structure:
<div ng-controller="GameController">
// some general HTML which fits all types of games
<div ng-controller="someScopeVar"> // Type of game
// some game-type-specific ng-models that should respond to the change of controller, i.e scope
</div
</div>
I saw here that it can be done within an ng-repeat
. Can it be done outside of it?
In other words, can I tell angular to read it as a variable rather than a string literal?
The way this works for
ngRepeat
is different. It works because it compiles each repetition, which is what you need to do here.For example:
We assign each controller function to
$scope.someScopeVar
, then we must compile a new element with the new controller and replace the old one.I don't believe angular has the capability to update a controller on the fly like that. Might be a good idea for a new feature.
FIDDLE
Another option would be to use the mixin pattern to update the main scope. You don't get a new shiny scope but it may work for your purposes.
FIDDLE
As discussed in the comments,
angular
has a really powerful feature/library for handling these scenarios -ui-router
(with its powerful wiki).The
ui-router
is an answer to need to develop functional pieces - states, rather then think in view/url (cite from a home page):There are some very interesting blog posts:
Exactly the point we need - decouple child states... dynamically change the controller in fact ... could be by url change or just a state change (one sibling child instead of other without url change)
Finally, there are few links, which I would mark as the saint grail of ui-router
Sample application. In action we can see, how the ui-router state machine does work. We can load list as a parent state, then we can select row items, which do represent their own child state... while parent is not reloading (here I tried to explain it in more details)
state.js
- the essential piece of code of the sample application. This is one of the best documented code snippets I've seen... Spent some time to go through and this will give you the 80% percent of answers: Howui-Router
is workingFrom my experience, this is really suitable for small apps as well as for large scale systems... love it...