angular ui router: component $onInit fires twice on route change

I am using angular-ui-router 0.2.18 with angular 1.5.x. I cannot explain why my component $onInit fires twice (I do not think it is relevant to my problem, but I am also using webpack).

My routing:

myModule.config(function ($stateProvider) {

    $stateProvider
    .state('app.project', {
        abstract: true,
        url: '/project',
        template: '<ui-view/>'
    })

    .state('app.project.demo', {
        url: '/demo',
        template: '<my-component></my-component>'
    });

});

A barebone version of my component:

myModule.component('myComponent', {
    template: require('./my-component.html'),
    bindings: {},
    controller: function () {

        this.alert = function () {
            console.log("fires");
        };

        this.$onInit = function () {
            this.alert();
        };

    }
});

Somewhere in my application, the route change is triggered by <a ui-sref="app.project.demo"></a> .

The alert function fires twice when I click the link, but not when I reload the page. Maybe the controller is loaded twice on route change ?

I have tried everything listed on this SO question: combating-angularjs-executing-controller-twice, but without success.

What really puzzles me though, is that the issue disappears when I rename my state name without changing anything else:

  • 'app.project.demos' works
  • 'app.projects.demo' works too (after changing 'app.project' to 'app.projects' of course)
  • What could be the explanation ?

    链接地址: http://www.djcxy.com/p/77952.html

    上一篇: 阻止$ state重新加载

    下一篇: angular ui router:component $ onInit在路由更改时触发两次