2017-05-07 79 views
0

如何在角度之間共享我所有狀態之間的變量「demo」?我試圖通過創建一個'mainController'並將它放置在我的狀態中以及另一個控制器在'視圖'中,如下所示。但是當我在我的州嘗試console.log(demo);時,我總是收到一個錯誤,說'演示'未定義。在AngularJS中共享狀態之間的值

我的主控制器

app.controller('mainController', function ($scope,$http,$state,$window,$timeout) { 
    var demo = "works"; 
}) 

我怎麼一直試圖G642.44各級我州內的「mainController」 一起在我的「看法」控制器(注:我已經關閉了支架上例如我展示你,但只是一個這個腳本以下大量的JavaScript)

.state('checkIn',{ 
    controller:'mainController', 
    url:'/checkIn', 
    views: { 
     'main':{ 
      templateUrl: 'templates/checkIn.html', 

      controller: function($scope,$http,$state,$window,$timeout){ 
       console.log(demo); 

我的JavaScript其餘

// Ionic Starter App 

// angular.module is a global place for creating, registering and retrieving Angular modules 
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) 
// the 2nd parameter is an array of 'requires' 
var app = angular.module('starter', ['ionic','ui.router','service']) 

.run(function($ionicPlatform) { 
    $ionicPlatform.ready(function() { 
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard 
    // for form inputs). 
    // The reason we default this to hidden is that native apps don't usually show an accessory bar, at 
    // least on iOS. It's a dead giveaway that an app is using a Web View. However, it's sometimes 
    // useful especially with forms, though we would prefer giving the user a little more room 
    // to interact with the app. 
    if (window.cordova && window.cordova.plugins.Keyboard) { 
     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
     cordova.plugins.Keyboard.disableScroll(true); 
    } 
    if (window.StatusBar) { 
     // Set the statusbar to use the default style, tweak this to 
     // remove the status bar on iOS or change it to use white instead of dark colors. 
     StatusBar.styleDefault(); 
    } 
}); 
}); 

app.controller('mainController', function ($scope,$http,$state,$window,$timeout) { 
    var demo = "works"; 
}) 

app.config(function($stateProvider,$urlRouterProvider,$httpProvider){ 
    $httpProvider.interceptors.push('AuthInter'); 

    $urlRouterProvider.otherwise('/home') 

    $stateProvider 
    .state('home',{ 
     controller:'mainController', 
     url:'/home', 
     views: { 
      'main':{ 
       templateUrl: 'templates/home.html', 

      } 
     } 
    }) 

    .state('signUp',{ 
     controller:'mainController', 
     url:'/signUp', 
     views: { 
      'main':{ 
       templateUrl: 'templates/signUp.html', 

       controller: function($scope,$http,$timeout,$state){ 
        $scope.register = function(){ 
         $scope.serverMsg =false; 

         $http.post('/signUp', $scope.newUser).then(function(data){ 
          $scope.serverMsg = data.data; 
          if($scope.serverMsg.success == true){ 
           $timeout(function(){ 
            $state.go('login'); 
           }, 2000); 
          } 
         }) 
        } 
       } 
      } 
     } 
    }) 
    .state('login',{ 
     controller:'mainController', 
     url:'/login', 
     views: { 
      'main':{ 
       templateUrl: 'templates/login.html', 
       controller: function($scope,$http,$timeout,$state,$window){ 
        $scope.setCurrentUser = function(user){ 
         $scope.currentUser = user; 
         console.log($scope.currentUser); 
        } 
        $scope.serverMsg = false; 

        $http.get('http://localhost:8080/users').then(function({ data: users }) { 
         $scope.users = users; 
        }) 
       } 
      } 
     } 
    }) 
    .state('checkIn',{ 
     controller:'mainController', 
     url:'/checkIn', 
     views: { 
      'main':{ 
       templateUrl: 'templates/checkIn.html', 
       // resolve: { 

       // }, 
       controller: function($scope,$http,$state,$window,$timeout){ 
        console.log(demo); 
        var today = new Date(); 
        var hour = today.getHours(); 
        var minute = today.getMinutes(); 
        var meridianPlaceHolder = today.getHours(); 
        meridianPlaceHolder = AmPm(meridianPlaceHolder); 
        minute = checkTime(minute); 
        hour = checkHour(hour); 

        //Handles Times 
        function AmPm(i){ 
        if(i < 12){ 
         return "AM"; 
        } 
        else{ 
         return "PM"; 
        } 
        } 

        function checkHour(i){ 
        if (i > 12){ 
         i = i - 12; 
        }; 
        return i; 
        } 

        function checkTime(i) { 
         if (i < 10) { 
         i = "0" + i 
         }; // add zero in front of numbers < 10 
         return i; 
        } 

        //var arrivalTime = document.getElementById("arrivalTime"); 

        //Sets a default input value for the arrivalTime 
        $scope.arrivalTime = hour + ":" + minute + " " + meridianPlaceHolder; 


        //arrivalTime.setAttribute("value", hour + ":" + minute + " " + meridianPlaceHolder); 

        //Checks whether or not the user has chosen a latop 
        var laptopQuery = false; 
        $('#yesLaptop').click(function(){ 
        laptopQuery = true 
        }); 

        $('#noLaptop').click(function(){ 
        laptopQuery = false 
        }); 

        //Handles the Inputs of the Check In Page 
        $scope.submit = function(){ 
        $scope.serverMsg = false; 
        console.log("Submitting Check In..."); 

        //Assigns a Random Laptop 
        var laptops = ["laptop2","laptop3","laptop4","laptop5","laptop6","laptop7","laptop8","laptop9","laptop10","laptop11","laptop12","laptop13","laptop14","laptop15","laptop16","laptop17","laptop18","laptop19","laptop20","laptop21","laptop22","laptop23","laptop24"]; 
        var laptop = laptops.splice([Math.floor(Math.random()*laptops.length)], 1); 

        //Retrieves input values 
        var timeLogArrival = document.getElementById("arrivalTime").value; 
        var timeLogDepature = document.getElementById("depatureTime").value; 
        var reasonForVisit = document.getElementById("reasonForVisit").value; 

        //Logs data, isn't currently working on monogo 
        console.log("Time of Arrival: " + timeLogArrival); 
        console.log("Time of Departure: " + timeLogDepature); 
        console.log("Reason for Visit: " + reasonForVisit); 
        //Displays whether or not a user checke out a laptop or not 
        if (laptopQuery){ 
        console.log("Your Laptop: " + laptop); 
        alert("Your Laptop: " + laptop); 
        } 
        else{ 
         console.log("You didn't check out a laptop"); 
        } 
        // var laptopUpdateQuery = {laptopId:laptop}; 
        // var userQuery = {'name':$scope.currentUser.name}; 
        // user.findOneandUpdate(userQuery,laptopUpdateQuery,function(err,doc){ 
        //  err ? console.log(err) : alert("success"); 
        // }) 
        $http.put('/check',$scope.currentUser).then(function(data){ 
          $scope.serverMsg = data.data; 
          if($scope.serverMsg.success == true){ 
          $timeout(function(){ 
           console.log("user data updated"); 
           $state.go('home'); 
          }, 2000); 
         } 
        }); 
        } 

        } 
       } 
      } 
     }); 
}); 

// this is for the phone number 
app.directive('phoneInput', function($filter, $browser) { 
    return { 
     require: 'ngModel', 
     link: function($scope, $element, $attrs, ngModelCtrl) { 
      var listener = function() { 
       var value = $element.val().replace(/[^0-9]/g, ''); 
       $element.val($filter('tel')(value, false)); 
      }; 

      // This runs when we update the text field 
      ngModelCtrl.$parsers.push(function(viewValue) { 
       return viewValue.replace(/[^0-9]/g, '').slice(0,10); 
      }); 

      // This runs when the model gets updated on the scope directly and keeps our view in sync 
      ngModelCtrl.$render = function() { 
       $element.val($filter('tel')(ngModelCtrl.$viewValue, false)); 
      }; 

      $element.bind('change', listener); 
      $element.bind('keydown', function(event) { 
       var key = event.keyCode; 
       // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing. 
       // This lets us support copy and paste too 
       if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)){ 
        return; 
       } 
       $browser.defer(listener); // Have to do this or changes don't get picked up properly 
      }); 

      $element.bind('paste cut', function() { 
       $browser.defer(listener); 
      }); 
     } 
    }; 
}); 

app.filter('tel', function() { 
    return function (tel) { 
     console.log(tel); 
     if (!tel) { return ''; } 

     var value = tel.toString().trim().replace(/^\+/, ''); 

     if (value.match(/[^0-9]/)) { 
      return tel; 
     } 

     var country, city, number; 

     switch (value.length) { 
      case 1: 
      case 2: 
      case 3: 
      city = value; 
      break; 

      default: 
      city = value.slice(0, 3); 
      number = value.slice(3); 
     } 

     if(number){ 
      if(number.length>3){ 
       number = number.slice(0, 3) + '-' + number.slice(3,7); 
      } 
      else{ 
       number = number; 
      } 

      return ("(" + city + ") " + number).trim(); 
     } 
     else{ 
      return "(" + city; 
     } 

    }; 
}); 

//Javascript for the Date to show in the input field by default 
// Time 


// controller: function($scope,$http,$timeout,$state,$window){ 
//     $scope.login = function(){ 
//      $scope.serverMsg =false; 

//      $http.get('mongodb://localhost:27017/cubeData', $scope.user.name).then(function(data){ 
//       $scope.serverMsg = data.data; 

//       if($scope.serverMsg.success == true){ 

//        $timeout(function(){ 
//         $state.go('checkIn'); 
//        }, 2000); 
//       } 
//      }); 
//     } 
//    } 
//   } 
//  } 
// }) 


    // $scope.loggingOut = false; 
         // $scope.logout = function(){ 
         //  $window.localStorage.removeItem('token'); 
         //  $scope.loggingOut = true; 
         //  $timeout(function() { 
         //   $state.go('signUp'); 
         //  }, 3000); 

         // } 

回答

3

有幾個方法可以做到這一點,在降正確性的順序。

首先 - 創建一個工廠/服務/價值/應用來保存這個共享值範圍內恆定的,包括它無處不在,你需要訪問的價值,最好的價值的getter/setter。

在以下示例中,這將是優選通過包括myService並調用myService.getMyObject()得到的值,但仍然可能 簡單地使用myService.myValue例如 -

app.service('myService', function() { 
    var service = { 
     myValue: 'some value', 
     myObject: { foo: 'bar' }, 
     getMyObject: function() { return service.myObject; }, 
     setMyObject: function(data) { service.myObject = data; } 
    }; 
    return service; 
}); 

- (這是怎樣的一個黑客,而不是一個很好的做法)是存儲在$ rootScope值。這使得它在全球範圍內可用 - 在控制器,服務和模板中。使用這種方法很容易污染,所以選項1是首選。

第三 - (不推薦)您可以按照您嘗試的方式進行操作,但這不可取。您必須使用controllerAs語法來定義您的控制器,並通過$scope.main.demo或不使用控制器A,通過$scope.$parent.demo <來訪問該值 - 這取決於嵌套而變得很難看,也很快混亂。

+0

第二我會說這也不被推薦,這是一個非常糟糕的做法。 順便說一句,爲了改進第一種方式,考慮到他只需要一個變量在整個應用程序中,那麼使用值並使用裝飾器來設置它呢? 'app.value( 'myVar的', '默認值');' '$ provide.decorator( 'myVar的',函數($代表){ 返回$代表+ '和相同的值更多的' ; });' – quirimmo

+0

同意,也不推薦第二種方式,但比第三個選項那麼糟糕:P 至於價值,這是提供一個值的絕佳解決方案。如果是這樣的目標(我想這是問題,特別是),那麼這就是他們所需要的。 假設OP希望訪問多個值或複雜類型,服務是一個更安全的/更廣泛地適用的解決方案。 – LouisK

+0

耶完全同意,如果他要分享許多東西,服務是最好的解決方案。 否則,對於一個變量,他可以只使用一個值,如果動態的,不斷不斷要是 – quirimmo

0

創建跨應用程序共享數據服務

1

正如@LouisK指出的那樣,第一種方法就是建議的方法。我還想說,如果你只想分享一個變量,你也可以考慮角value,否則服務是正確的。

app.value('myVar', 'Default Value'); 

爲了改變它:

$provide.decorator('myVar', function ($delegate) { return $delegate + ' and same value more'; }); 

然後,只需注入myVar在您需要。