$ scope在函数AngularJS中不起作用

时间:2014-04-03 08:33:56

标签: html angularjs angularjs-scope

我的代码:

HTML

<body ng-app="loginApp" ng-controller="loginCtrl" > <div class="loginWrap" > <input type="text" placeholder="Username " ng-model="user" /> <input type="text" placeholder="Password " ng-model="pass" /> <input type="button" value="Login" ng-click="checkLogin()" /> <span ng-bind="resultLog"></span> </div> </body>

Angular Code :::

 var appLog = angular.module('loginApp',[])
 .controller('loginCtrl',function($scope,$http){

 $scope.checkLogin = function(){

  if($scope.user.length > 0 && $scope.name.length > 0  )
  {
      $http.post('php/checkLogin.php',{'n':$scope.user, 'p':$scope.pass})
         .success(function(data)
         {
            if(data)
            {
                $scope.resultLog = "Valid"
            }
             else
            {
                $scope.resultLog = "InValid"
            }
         })
         .error(function()
         {
           $scope.resultLog="Error"
         })
  }
  else
  {
    $scope.resultLog = "Fill All Fields";
  } // end of validation


 } })

我正在学习角度JS ..并执行一些..

问题:: $scope.resultLog无效

范围Obejct无法在函数内部工作.. 它在LoginCtrl和。中声明 我在函数内部使用,在LoginCtrl中声明

提前致谢

2 个答案:

答案 0 :(得分:2)

在您的控制器中,您使用$scope.name,它指向什么?,因为您有ng-model="user",而不是ng-model="name"

您的输入未直接指向user.name,而是指向user。你想改变它:

<input type="text" placeholder="Username " ng-model="user.name" />

并在您的控制器中:

$scope.checkLogin = function(){

  $scope.user = {};    

  if($scope.user.name.length > 0 && $scope.user.name.length > 0  )

  //......

}

答案 1 :(得分:1)

您必须初始化username,否则它将未定义,因此您无法检查未定义 <的长度/ p>

试试这个

Working Demo

var appLog = angular.module('loginApp',[]);

appLog.controller('loginCtrl',function($scope,$http){
$scope.user="";
$scope.pass="";
$scope.checkLogin = function(){

if($scope.user.length > 0 && $scope.pass.length > 0  )
{
      $http.post('php/checkLogin.php',{'n':$scope.user, 'p':$scope.pass})
         .success(function(data)
         {
            if(data)
            {
                $scope.resultLog = "Valid"
            }
             else
            {
                $scope.resultLog = "InValid"
            }
         })
         .error(function()
         {
           $scope.resultLog="Error"
         })
}
else
{
  $scope.resultLog = "Fill All Fields";
} // end of validation

} });