gpt4 book ai didi

javascript - 在 AngularJS 中的状态之间共享值

转载 作者:行者123 更新时间:2023-11-28 14:53:10 27 4
gpt4 key购买 nike

如何在 Angular 的所有状态之间共享变量“demo”?我尝试通过创建一个“mainController”并将其与“ View ”中的另一个 Controller 一起放置在我的状态中,如下所示。但当我在我的州尝试 console.log(demo); 时,我不断收到一条错误消息,提示“demo”未定义。

我的主 Controller

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

我如何尝试将我的状态中的“mainController”与“ View ”中的 Controller 一起集成(注意:我已经在我的示例中关闭了括号向您展示,此脚本下面只有很多 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);

// }

最佳答案

有几种方法可以做到这一点,按正确性降序排列。

首先 - 在应用程序中创建一个工厂/服务/值/常量来保存此共享值,并将其包含在您需要访问该值的任何地方,最好使用该值的 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 上。这使得它在 Controller 、服务和模板中全局可用。这种方式容易造成污染,所以优先选择方案1。

第三 - (不推荐)您可以按照您尝试的方式进行操作,但不建议这样做。您必须使用 controllerAs 语法定义 Controller 并通过 $scope.main.demo 访问该值,或者不使用controllerAs,通过 $scope 访问该值。 $parent.demo <-- 这会很快变得丑陋且令人困惑,具体取决于嵌套。

关于javascript - 在 AngularJS 中的状态之间共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43835542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com