简体   繁体   中英

Angular ui-router runs controller twice on load if it is specified in the $stateProvider

I am seeing that code in my controller is being ran twice , thus showing in the console.log windows output in chrome dev tools

questions.html

<div ng-controller="questionController as vm"> </div>

questionController.js

var questionController = function($location, questionService, $env) {
    var vm = this;
    console.log('in the controller')  // this runs twice 
}

app.js

app.config([
    '$stateProvider',
    '$urlRouterProvider',
    '$locationProvider',
    function ($stateProvider, $urlRouterProvider, $locationProvider) {

        var viewBase = '/apps/src/views/';

        $urlRouterProvider.otherwise("/");

        $locationProvider.hashPrefix(''); // get rid of ! was getting #! 

        $stateProvider
            .state('questions',
            {
                url: "/questions",
                templateUrl: viewBase + "questions.html"//,
                //controller: "questionController"
                //views: {
                //
                //}
            });


    }]
);

Notice that I commented out the controller: "questionController" in the route, otherwise it ran twice.

I know that I used ui-router last year and i always used controller: without any problems.

Perhaps some new version combinations causing a bug?

Based on an answer i was trying but not data not displaying

I am using ui-grid

 <!--<div ng-controller="questionController as vm">-->

       <div ui-grid="{ data: vm }" class="grid"></div>

  <!--</div>-->

Notice i commented out div with the ng-controller

  var vm = this
  var promise = questionService.getAllQuestions();

    promise.then(function(response) {
        vm.myData = response;
        console.log('questionCtrl promise data', vm.myData);
    });

The console.log does work to spit out data

Fixed

Seems that I had to do

route

     controller: "questionController",
     controllerAs : "vm"

OR

      controller: "questionController"

Then

 <div ui-grid="{ data: vm.myData }" class="grid"></div>

This is because you are including the controller in your $stateProvider as well as the template itself by doing

<div ng-controller="questionController as vm"></div>

You can remove ng-controller from your HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM