简体   繁体   中英

Ionic popup confirm is not executing code in an if statement

I have code behind a button that, once pressed, the button is meant to call a function to throw a pop up on screen. Either way if the user selects ok or dance, another function will be called. The problem is neither of these two functions are being called. Am I missing something very obvious?

$scope.user = {};
// A confirm dialog
$scope.showConfirm = function() {
var confirmPopup = $ionicPopup.confirm({
               title: 'T&Cs',
               template: 'Do you agree to the terms and conditions?'
               });
confirmPopup.then(function(res) {
               if( res ) {
                   signIn(user)
               } else {
                   logout();
               }
        });
  };

When working in javascript you need to understand scope. This is best explained here... w3schools.com/js/js_scope.asp.

In brief:

$scope is predefined in a controller (angular) and as such is available anywhere in that one controller. $rootScope is available in all controllers. Please see this example of scope:

.controller('ctrl1', function($scope, $rootScope) { 

    var a = 1;
    $scope.a = 2;
    $rootScope.a = 3;

    var funct1 = function () {

        var b = 4;
        $scope.b = 5;
        $rootScope.b = 6;

        console.log(a) // returns 1 as inherits scope 
        console.log($scope.a) // returns 2 as inherits $scope scope
        console.log($rootScope.a) // returns 3 as inherits $rootScope scope 

        console.log(b) // returns 4 as shares scope 
        console.log($scope.b) // returns 5 as inherits $scope scope
        console.log($rootScope.b) // returns 6 as inherits $rootScope scope 


    }

    funct1();

    console.log(a); // returns 1 as shares scope
    console.log($scope.a); // returns 2 as inherits $scope scope
    console.log($rootScope.a); // returns 3 as inherits $rootScope scope
    console.log(b); // returns undefined as b is defined out of scope.
    console.log($scope.b); // returns 5 as inherits $scope scope
    console.log($rootScope.b); // returns 6 as inherits $rootScope scope

})

Assuming the code in ctrl1 has already executed the only defined variables accessible from other controllers would be $rootScope.a and $rootScope.b. All others would be out of scope and as such undefined.

This is an oversimplification but serves to explain $scope and $rootScope in angular to beginners.

A common mistake is to confuse the definition of variables and objects $scope and $rootScope with var x = y; Check this first ie users vs $scope.users, if this is ok then look at scope as the next test.

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