My function is called 3 times and I don't know why


#1

Hi there,

I have a problem that I can’t understand…

I have this code :

.controller('AppCtrl', function ($scope, $ionicModal, $timeout, $http, $state, $compile) {

    $timeout(function () {
            if ($state.current.name === "app.home") {
               $scope.loadUserData();
            }
            
    },100);

$scope.loadUserData = function() {
    if(localStorage.getItem('uniqueUser')!= null && localStorage.getItem('uniqueUser')!= undefined && localStorage.getItem('uniqueUser')!= ""){
        console.log("if");
        var usr = JSON.parse(localStorage.getItem('uniqueUser'));
        var divMere = document.getElementById('divMere');
        divMere.innerHTML = '<div class="item item-text-wrap"> Vous êtes connecté avec l\'adresse ' + usr.email + '</div>';
        
    }
    else //(localStorage.getItem('uniqueUser') == null || localStorage.getItem('uniqueUser') == undefined || localStorage.getItem('uniqueUser') == "")
    {

        console.log("show");
    }
    console.log("loadUserData()");   
);

And in the console i got this result :

show
controllers.js:98 loadUserData()
controllers.js:96 show
controllers.js:98 loadUserData()
controllers.js:96 show
controllers.js:98 loadUserData()
controllers.js:96 show
controllers.js:98 loadUserData()

So my function loadUserData() seems to be called 3 times… and I don’t know why…

If someone can help me ? :smile:

BR,

OxoGau !


#2

maybe you connected the controller to multiple views at the same state?
or to multiple dom-elements

or you are calling the $scope-function directly in the templates?


#3

Maybe a lowdash function runonce will help