Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs controller executes 2 times

I have a problem where a controller executes twice, yet I do not have duplicates that i can see (even running a case sensiTIve search through my files only shows one in route configuration and my actual controller).

Route config:

$routeProvider.when('/cb159e1ec61d0613f10ab397d8bd6782',{
    templateUrl: view+'passwordreset.html',
    controller:'passwordreset'
});

Controller:

App.controller('passwordreset',['$scope','$http',
    function($scope,$http){
        $scope.token='asdf'
        console.log($scope.token); // <-- logs 2x to console
}]);

passwordreset.html:

<div class="row">
    <div class="small-12 columns">
        <fieldset class="content-box">
            password reset {{token}}
        </fieldset>
    </div>
</div>

Also, I've created a new route and tried, still logs twice. I've cleared my cache as well. Some controllers execute once, some twice (I put an alert in a few controllers, some show once, some twice)

another example:

//route config
    $routeProvider.when('/', {
     templateUrl: view+'home',
     controller:'Home'
    });

//template   
        <div ng-controller="testing">a</div>
//controller
Lmu.controller('Home',function($scope){
    $scope.home='home';
    alert($scope.home); <-- alerts 2x (two scopes for Home controller are created)
});
like image 924
Eric Shell Avatar asked Oct 14 '25 04:10

Eric Shell


1 Answers

I figured out the problem. I had two layouts depending on whether the user was authorized using ng-show="user.authorized" and ng-show="!user.authorized". Each had a <div ng-view>. Every ng-view gets processed whether ng-show is true or false.

I didn't realize everything in ng-show gets processed whether true or not.

Fix: used ng-switch instead of ng-show. This keeps the view from being processed until the condition is met.

like image 76
Eric Shell Avatar answered Oct 16 '25 18:10

Eric Shell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!