Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ui-sref" does not refresh the "ui-view"(its controller does not rerun) when a link is clicked twice

When a state is clicked at first, the div that owns the "ui-view" attribute is replaced with the "template" of that state. However, when I click the same state again, its controller does not reloaded. How can I make this controller to load again?

For example, suppose I have the following navigation menu:

<nav> 
    <a ui-sref="state1">State 1</a>
    <a ui-sref="state2">State 2</a>
</nav>

My "ui-view" content is as follows:

<div ui-view></div>

My states are described as below. When I click the "State1" on the navigation menu, I expect to observe the text "Ctrl 1 loaded" on the developer console. If it's first time, then I observe that text. However, when I re-click the same link, the controller is not loaded again that is I couldn't see the text "Ctrl 1 loaded" displayed on the console twice.

myApp.config(function ($stateProvider, $urlRouterProvider){
    $stateProvider.state("state1", {
        url: "#",
        template: "<p>State 1</p>",
        controller: "Ctrl1"
      }).state("state2", {
        url: "#",
        template: "<p>State 2</p>",
        controller: "Ctrl2"
      });
});

Why? Do you have any idea?

Here is the JSFiddle of this question.

like image 402
ankakusu Avatar asked Aug 06 '14 08:08

ankakusu


3 Answers

Like Philipp said, it is because this is the default behavior of ui-router, BUT if you would like to reload your controller each time you click on your link, you can actually use the ui-sref-opts attribute to force it, like this:

<a ui-sref="state1" ui-sref-opts="{reload: true}">State 1</a>

Found this tip here:

https://github.com/angular-ui/ui-router/commit/91a568454cc600aa4f34dedc8a80c9be1130b1c5

Hope it could help

like image 159
schankam Avatar answered Nov 15 '22 12:11

schankam


Alternative syntax to go to a different view it would be

<a ui-sref="state1({reload: true})">State 1</a>

On the controller it would look like this.

$state.go('state1', {}, {reload: true});

Note: The second parameter of $state.go is $stateParams.

like image 34
Rick Avatar answered Nov 15 '22 10:11

Rick


Because that's how ui-router is designed.

The controller is only loaded when it isn't in the same state. ui-router will not rerun a controller, and not reevaluate a view template. Even when you use the same controller on multiple states and switch between those, the controller will not rerun.

If you want to run functionality when the a view changes you could listen for events, or even put an ng-click on your a element.

like image 36
Philipp Gayret Avatar answered Nov 15 '22 10:11

Philipp Gayret