切换值未更新

时间:2017-03-11 17:59:38

标签: angularjs ionic-framework

我有一个切换,如果你从false改变它的值 - >如果为true,将弹出一个模态并要求您登录。如果登录成功,则切换值应保持为True。如果登录过程出现问题(凭证无效),则切换应返回False。

app.controller('AppCtrl', function($scope, $localStorage, $http, $ionicModal, $timeout, $state, md5) {

$scope.invertToggle = function () {
  $localStorage.value = !$localStorage.value;
  $scope.value = $localStorage.value;
  console.log("Toggle New Value = " + $scope.value);
}

$scope.setToggleTrue = function() {
  $localStorage.value = true;
  $scope.value = true;
  console.log("Toggle New Value = " + $scope.value);
}

$scope.setToggleFalse = function() {
  $localStorage.value = false;
  $scope.value = false;
  console.log("Toggle New Value = " + $scope.value);
}

 $scope.change = function() {

  $scope.invertToggle();

  $ionicModal.fromTemplateUrl('templates/modal.html', function(modal) {
    $scope.modal = modal;
  }, {
    animation: 'slide-in-up',
    backdropClickToClose: false,
    hardwareBackButtonClose: false,
    focusFirstInput: true
  });


  if ($localStorage.value == true) {
   console.log("Modal will pop up");
   $scope.modal.show();
  } else {
    console.log("Unregister device");
  }
 }
$scope.submit = function() {


    if (res.data != "Wrong Credentials") {
      //We are not changing the toggle value here since login is ok
    }
    else{
      $scope.setToggleFalse(); //login details were invalid, so we are setting toggle to false
    }

   })

   .catch(function(error) {
    console.error(error);

    if (error.statusText == ""){
      $scope.response = "Unexpected error. Make sure WiFi is on."
    }
    else {
      $scope.response = "Error - "+error.status + " ("+error.statusText+")";
    }
    $scope.setToggleFalse(); //Unfortunatly here, an error occured so, we setting the Toggle back to False, just to be safe   
   })

   .finally(function() {
    console.log("Finally Function");
    $timeout(function(){
        $scope.modal.hide(); // we are hiding the modal, so the user returns to the previous page
        $scope.$apply(function () { //I found somewhere $apply can do the trick but no luck
          $scope.value = false; // Here I manually set the variable to false but again the toggle is still on on the page.
        });
     }, 3000);

   });
 };
});

这是切换html:

<ion-toggle ng-model="value"  ng-checked="value" ng-change="change()"toggle-class="toggle-royal">Register Device</ion-toggle>

如何自动刷新页面上的变量?我尝试将缓存设置为false,再次没有运气。我知道代码很乱,但是一旦一切都处于工作状态,我就会用亨利胡佛来清理污垢。 :)

1 个答案:

答案 0 :(得分:1)

尝试通过传入范围参数:

让模态访问原始控制器的范围
$ionicModal.fromTemplateUrl('templates/modal.html', function(modal) {
    $scope.modal = modal;
  }, {
    scope: $scope,  /// GIVE THE MODAL ACCESS TO PARENT SCOPE
    animation: 'slide-in-up',
    backdropClickToClose: false,
    hardwareBackButtonClose: false,
    focusFirstInput: true
  });