Controller called twice at view first load


#1

I have a view that, at it`s first load, the controller is firing every funcion twice. If I press back button and go back to the view, this behavior stops and everything goes back to normal. Is this some kind of bug?

The controller is only set once in routing.

$stateProvider

.state(‘quantidade’, {
url: ‘/quantidade/:codigoProduto/:precoProduto/:descricaoProduto’,
templateUrl: ‘templates/quantidade.html’,
controller: ‘QuantidadeController’
})

This is my index.html dependencies:

<link href="Content/ionic.css" rel="stylesheet" />
<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/1.4.1/css/ionicons.min.css">
<script src="scripts/ionic.bundle.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<link href="css/index.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet">
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>

This is my controller, function ‘mais’ is called twice when I click the button:

.controller(‘QuantidadeController’, function ($scope, $rootScope, $state, RedeVictorServices, $stateParams, $ionicPopup) {

$scope.codigoProduto = $stateParams.codigoProduto;
$scope.descricaoProduto = $stateParams.descricaoProduto;
var str = $stateParams.precoProduto;
var num = parseFloat(str.replace(',', '.').replace(' ', ''));
$scope.valorProduto = num;
$scope.precoAcumulado = num;
$scope.quantidade = 1;

if ($rootScope.qtdCheck == 1) {
    $rootScope.qtdCheck = 2;
    $state.go($state.current, {}, { reload: true });
}

$scope.mais = function () {
    $scope.quantidade = $scope.quantidade + 1;
    $scope.precoAcumulado = num * $scope.quantidade;
}

#2

Does your ‘templates/quantidade.html’ HTML file is having ng-controller defined?


#3

No, Its not defined.
I only set this in routing


#4

Anyone can help me???


#5

I know its been a while, But to help others in future, I am writing this reply.

If the controller is called in the abstract route then $ionicView.loaded is executing twice, I think one for abstract view and other for the child view. To overcome, i moved my logic to $ionicView.beforeEnter, which execute only once, when the child view is loaded.

My state configuration looks as below.

.state('main.settings', {
                    url: "/settings",
                    abstract:true,
                    views: {
                        'menu-content': {
                            template:'<ion-nav-view name="settings-view"></ion-nav-view>',
                            controller:"settingsCtrl as vm"
                        }
                    }

})
.state('main.settings.account', {
                        url: "/account",
                        views: {
                            'settings-view': {
                                templateUrl: "app/pages/settings/account.html"
                            }
                        }
})