2

I'm using the state definitions below(UI-Router's). Once I invoke $state.go('products.new') the controller (ProductCtrl) is invoked twice.

For some reason, UI Router "forgets" the original state change and invokes the controller based on the url only (which is indeed ambiguous in this case).

If I arrive at the page directly though (deep link) the controller is invoked once as it should.

Any suggestion how to make it work?

.state('products', {
    abstract: true,
    template: "<div ui-view></div>"
})

.state('products.product', {
    url: '/products/:productId',
    templateUrl: 'views/productView.html',
    controller: 'ProductCtrl'
})

.state('products.new', {
    url: '/products/new',
    templateUrl: 'views/productView.html',
    controller: 'ProductCtrl'
})
user1140419
  • 111
  • 1
  • 6

3 Answers3

6

It could be many things but you don't provide much details about your view:

It could be having the binding between controller and view in the routing (as you have it) and ALSO having a reference to ng-controller="ProductCtrl" in the view as @veroxii suggests so the routing is invoking the controller as soon as the URL is requested and later again as soon as the view is loaded.

But it could also be that you are using something like UI Router with bootstrap tabs or similar (I had this issue) and you were loading the <div ui-view></div> inside the tab (nested views). In that case the controller might be invoked N times being N the number of <div ui-view></div> in the view. Moving the <div ui-view></div> outside the tab and tabset solved the problem to me.

diegosasw
  • 13,734
  • 16
  • 95
  • 159
5

I just had the same problem using $state.go. Turns out it was really this problem and I'm going to guess you have ng-controller="ProductCtrl" somewhere in your HTML and a controller defined on your state:

https://stackoverflow.com/a/15535724/2172360

Community
  • 1
  • 1
veroxii
  • 500
  • 4
  • 6
0

I am also facing same issue. If we are using following syntax :

.state('products.product', { url: '/products/:productId', templateUrl: 'views/productView.html', controller: 'ProductCtrl' })

then no need to add controller in your productView.html file. This is reason for twice controller initialisation. Please remove

your view

like syntax from your html file