简体   繁体   English

在AngularJS中的状态之间共享值

[英]Sharing values between states in AngularJS

How can I share the variable "demo" between all of my states in angular? 如何在角度的所有状态之间共享变量“演示”? I've tried to do this by creating a 'mainController' and placing it inside of my states along with another controller in the 'view' like shown below. 我试图通过创建一个'mainController'并将其与另一个控制器一起放置在我的状态内,如下图所示,将其放置在我的状态之内。 But I keep getting an error saying that 'demo' is not defined when I try console.log(demo); 但是当我尝试console.log(demo);时,我一直收到错误消息,说“ demo”未定义console.log(demo); in my states. 在我的州。

My Main Controller 我的主控制器

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

How I've tried to intergrate that 'mainController' within my states alongside a controller in my 'view' (NOTE: I've closed the brackets on the example I'm showing you, there's just a lot of javascript below this script) 我如何在州内 “视图”中的控制器整合该“ mainController” (注意:我已经关闭了在向您展示的示例中的括号,此脚本下方只有很多JavaScript)

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

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

The rest of my javascript 我的其余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);

                        // }

There are a few ways to do this, in descending order of correctness. 有几种方法可以按照正确性的降序排列。

First - Create a factory/service/value/constant within the app to hold this shared value and include it everywhere you need to access the value, preferably with a getter/setter for the value. 首先 -在应用程序中创建一个工厂/服务/值/常量来保存此共享值,并将其包含在您需要访问该值的任何位置,最好使用该值的获取器/设置器。

In the following example, it would be preferable to get the values by including myService and calling myService.getMyObject() , but still possible to simply use myService.myValue eg - 在以下示例中,最好通过包含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;
});

Second - (This is kind of a hack and not a good practice) is to store the value on the $rootScope. 第二 -(这是一种技巧,不是一种好习惯)是将值存储在$ rootScope上。 This makes it globally available - in controllers, services, and templates. 这使其在控制器,服务和模板中全局可用。 It's easy to pollute using this method, so option 1 is preferred. 使用此方法很容易污染,因此首选选项1。

Third - (not recommended) You could do it the way you are trying, but it's not advisable. 第三 -(不推荐)您可以按照尝试的方式进行操作,但是不建议这样做。 You'd have to either use the controllerAs syntax defining your controllers and access the value through $scope.main.demo , or without controllerAs, through $scope.$parent.demo <-- this gets ugly and confusing fast, depending on nesting. 您将不得不使用controllerAs语法定义您的控制器,并通过$scope.main.demo访问值,或者不使用controllerAs通过$scope.$parent.demo <-访问此值,这会很丑陋且令人困惑,具体取决于嵌套。

As @LouisK pointed out, the first way it's the suggested one. 正如@LouisK所指出的,第一种方法是建议的方法。 I would say also that you can consider the angular value too if you want to share just one single variable, otherwise services are the right way. 我还要说,如果只想共享一个变量,也可以考虑角度value ,否则服务是正确的方法。

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

In order to change it: 为了更改它:

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

Then simply inject myVar where you need. 然后只需在需要的地方注入myVar

创建服务以在整个应用程序中共享数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM