Faizah Pratiwi Faizah Pratiwi - 1 month ago 6
AngularJS Question

Cannot read property 'username' of undefined in angularjs

i want make a login with angularjs and ionic. but when i run this program, this program is error. the error is :


TypeError: Cannot read property 'username' of undefined


anyone help me?

form :

<body ng-app="apps" ng-controller="PostController as postCtrl">
<ion-view view-title="Please Sign in">
<ion-content class="padding">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Name" ng-model="postCtrl.inputData.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="postCtrl.inputData.password">
</label>
</div>
<div class="alert alert-danger" role="alert" ng-show="errorMsg">{{errorMsg}}</div>
<button class="button button-full button-balanced" ng-click="postForm()">Sign In</button>
</ion-content>
</ion-view>
<script src="controller.js"></script>
</body>


controller :

angular.module('apps', ['ionic'])
.controller('PostController', ['$scope', '$http', function($scope, $http) {

$scope.postForm = function() {

var encodedString = 'username=' +
encodeURIComponent(this.inputData.username) +
'&password=' +
encodeURIComponent(this.inputData.password);

$http({
method: 'POST',
url: 'check-login.php',
data: encodedString,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config) {
console.log(data);
if ( data.trim() === 'correct') {
window.location.href = 'home.html';
} else {
$scope.errorMsg = "Login not correct";
}
})
.error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
})
}

}]);

Answer

In your controller do

var self = this;
self.inputData = {};

And replace
this.inputData.username with self.inputData.username
this.inputData.password with self.inputData.password

Comments