Javascript范围在角度SPA应用程序中不起作用

Javascript scope does not work in angular SPA app

本文关键字:应用程序 不起作用 SPA 范围 Javascript      更新时间:2023-09-26

所以我有这个角度的SPA,index.html包含

var app = angular.module('app', ['ngRoute']);   

        app.config(function ($routeProvider , $locationProvider) {         
            $routeProvider                                     
            .when('/', {                      
               templateUrl: 'home.html',                         
               controller: 'homeController'                    
           })                    
            .when('/login', {                     
               templateUrl: 'login.html',                        
               controller: 'loginController'                    
           })                    
     }); 

    app.controller('homeController', function ($scope) {            
            $scope.message = 'Welcome';        
    }); 
    app.controller('loginController', function ($scope) {            
            $scope.message = 'Login';            
    }); 

  <div ng-view></div> 

所以我在已经包含javascript的index.html中注入了html和javascript。

登录文件类似于

 <p>{{ message }}</p>
    <form >
            <input type="text"  id="username" name="username">
            <input type="password" id="password" name="password">        
            <button type="submit" id="login"> Login </button>
    </form>       
    <script type="text/javascript">         
    document.getElementById("login").onclick = handleButtonPress;
    function handleButtonPress(e) {
        e.preventDefault();
        alert("hey, sup?");
        var form = document.getElementById("loginform");
        var formData = new FormData(form);
        var j = JSON.stringify(formData);
        alert(" formData  > " + j.username);    
      }
    </script>

我的问题是,在login.html文件中,它不会像应有的方式提醒alert("hey, sup?");,也不会提醒用户名。

我想 javascript 范围有问题,因为index.html中有一个,login.html中有一个。

login.html里面,如果我做一个简单的

<button onclick="hey()"> Click </button>
function hey(){    
    alert("hey");    
}

我得到Uncaught ReferenceError: hey is not defined.

那么这里的javascript有什么问题,我该如何解决这个问题?

谢谢

既然你使用的是角度,那么使用角度的东西呢?

app.controller('loginController', function ($scope) {            
        $scope.message = 'Login'; 
        $scope.loginData = {};
        $scope.hey = function(){
            alert('hey '+$scope.loginData.username);
        }           
}); 
<input type="text"  id="username" name="username" ng-model = "login.Data.username">
<input type="password" id="password" name="password" ng-model="loginData.password">       
<button type="submit" id="login" ng-click="hey()"> Login </button>

使用角度,您可以使用表单验证,基本的东西真的很容易在网上找到。如果您需要向服务者提出请求,谷歌$http基础知识。