2016-10-01 75 views
0

我试图通过验证存储在json文件中的数据的凭据来实现登录表单。但我越来越喜欢只有第​​一种情况的错误是working.It只是一个演示应用程序试图了解的概念: 这是我的控制器:在angular.js中登录表单

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

app.controller("myCtrl",function($scope, $http) 
{ 
     $scope.check = function(){ 
      var sample; 
        $http.get('roles.json').then(function(res) 
        { 
         sample = res.data; 

        console.log(sample); 

        angular.forEach(sample, function(val) 
        { 
         if($scope.uName===val.userName) 
         { 
          if($scope.password===val.password) 
          { 
           alert("sucess"); 
          } 
          else 
          { 
           alert("failure"); 
          } 
         } 
         else 
         { 
          alert("failure"); 
         } 

        }); 
       }); // end of http 
     };// end of function 
}); 

数据被正确加载,但似乎在逻辑上有些问题。 数据JSON:

[ 
    {"userName":"stud101","password":"stud1","role":"student"}, 
    {"userName":"stud102","password":"stud2","role":"student"}, 
    {"userName":"superlib","password":"lib1","role":"Librarian"} 
    ] 

我只得到与第一例成功,其余的其他情况下的故障。

+0

你的HTML看起来像什么?什么是确切的错误信息? – nikjohn

+0

如果要将密码和用户名发送到浏览器,登录没有任何意义。任何人都能看到它们。有了这样的说明...告诉我们什么样的数据看起来像我们可以帮助你做什么你有工作 – charlietfl

+0

你的条件是检查uName和密码是否等于val,它似乎有点奇怪。请检查 –

回答

0
angular.forEach($scope.messagepool, function(value, key) { 
    if(value.userName==$scope.uName && value.password==$scope.password){ 
    alert('success'); 
    }else{ 
    alert('faluire'); 
    } 
}); 

使用此代替您的foreach。希望这有助于(y)

1
$http.get('roles.json').then(function(res){ 
    sample = res.data; 

    console.log(sample); 
    var isMatched = false; 
    angular.forEach(sample, function(val) 
    { 
    if($scope.uName==val.userName && $scope.password==val.password) 
    { 
     isMatched = true; 
     return false; // To stop the foreach loop if username and password both are matched. 
    } 


    }); 
    if(isMatched) 
    { 
    alert("success"); 
    } 
else 
{ 
    alert("failure"); 
} 
});