I am new in Ionic and angularjs. I am trying to fetch login (ng-model) data (email&password) from signin.html page, and calling API with POST method.But it doesn't call api. I spent couple of days for this. Please help me!
html
<ion-view view-title="login">
<ion-component>
</br>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="First Name" ng-model="login.firstname">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="login.password">
</label>
<label class="item item-input">
<input type="text" placeholder="E-mail" ng-model="login.email">
</label>
<button class="button button-block button-balanced" data-ng-click="submit(login)">
Login
</button>
<button class="button icon-left button-block ion-social-facebook button-positive">Login Facebook</button>
<button class="button icon-left button-block ion-social-googleplus button-assertive">Login Google+</button>
<a ng-href="#/signup"><button class="button button-clear button-positive">SignUp
</button></a>
</div>
</ion-component>
</ion-view>
app.js
var app=angular.module('starter', ['ionic','ngCordova'])
app.controller('loginCtrl', function($scope,$http){
$scope.data=[];
// $scope.logindata = {};
// console.log (login);
$scope.login={};
//****login submit****
$scope.submit=function(login){
console.log(login);
$scope.logincontet=console.log('logindata:'+login);
//***api call***
var local1='json={"method_name":"login","body":{"login_with":"2","facebook_id":"","email":';
var local2=',"name":"",';
var local3='"password":';
var local4='}}';
var req =
{
method: 'POST',
url: "http://192.168.1.23/projects/veterinary/webservice/main.php",
//data: 'json={"method_name":"login","body":{"login_with":"2","facebook_id":"","email":"$scope.login.email","name":"","password":"$scope.login.password"}}',
data:local1 + $scope.login.email + local2 + local3 + $scope.login.password +local4,
headers: {"Content-Type": "application/x-www-form-urlencoded"}
};
$http(req).success(function(data, status, headers, config)
{
console.log('Success',data);
$scope.data=data.data;
//success
})
.error(function(data, status, headers, config)
{
console.log('Error');
});//error
//*********
window.location.href = "#/success.html";
}
//*****
//****login api call****
});
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
controller: 'loginCtrl'
})
.state('signup', {
url: "/signup",
templateUrl: "templates/signup.html",
controller: 'signupCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
*********************
Binding view and controller!
Finally I created post api string with this...
data: 'json={"method_name":"login","body":{"login_with":"2","facebook_id":"","email":"'+$scope.login.email+'" ,"name":"","password":"'+$scope.login.password+'"}}',
Related
I have created a new project, but got a problem which I am not able to fix.
Here's my example:
I have this error :
"Error: [$controller:ctrlreg] The controller with the name 'PostController' is not registered."
Connexion.html
<section id="login" ng-controller="PostController as postCtrl">
<div class="container center-bloc">
<div class="row">
<div class="col-xs-12">
<div class="form-wrap">
<div class="text-center">
<img id="logo" style="max-width:100%;" src="img.png">
</div>
<h2 id="ResultConnexion"></h2>
<form role="form" id="login-form" ng-submit="postCtrl.Search1()" method="POST" autocomplete="off">
<div class="form-group">
<input id="userLogin" required autofocus ng-model="postCtrl.inputData.username" type="text" name="user" id="email" class="form-control" placeholder="exemple#example.com">
</div>
<div class="form-group">
<input id="userPassword" required ng-model="postCtrl.inputData.password" type="password" name="mdp" id="key" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block" ng-disabled="login.$invalid" >Connexion</button>
<div class="alert alert-danger" ng-show="errorMsg">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×</button>
<span class="glyphicon glyphicon-hand-right"></span> {{errorMsg}}
</div>
<div></div>
</form>
<hr>
</div>
</div>
</div>
</div>
index. js
'use strict';
var routeApp = angular.module("routeApp", ["ngRoute"]);
routeApp.config(function($routeProvider) {
$routeProvider
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController"
})
});
var routeAppControllers = angular.module('routeAppControllers',['ngRoute']);
routeAppControllers.controller('PostController', ['$scope', '$http', function($scope, $http) {
this.postForm = function() {
var Pass = {"user":(this.inputData.username),"mdp":(this.inputData.Password)};
$http({
method: 'POST',
url: '/',
data: Pass,
headers: {'Content-Type': 'application/json'}
})
.then(function(response) {
if ( response.data.resultat == 0) {
window.location.href = '/information';
alert('hello')
} else {
$scope.errorMsg = 'Bad';
}
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}
}]);
Can anybody help?
You have two separate modules showing and neither is injected in the other.
Assuming your ng-app uses routeApp you need to inject routeAppControllers module into routeApp module
var routeApp = angular.module("routeApp", ["ngRoute", "routeAppControllers"]);
Also you only need to inject ngRoute once.
As noted in other answer you only use ng-controller when it is not declared in routing config also, or you end up with multiple controller instances
I think you should remove ng-controller="PostController as postCtrl"> from template .Because you defined it in route . and also change to below.
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController as postCtrl"
})
another tip that recommended you declare var vm = this and use vm instead of this
vm.postForm = function() {...}
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';
})
}
}]);
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
I tried a sample. Look at this
$scope.inputData = {
username: null,
password: null
}
http://jsfiddle.net/JKBbV/1179/
You can just do it in the angular way, like below.. that should be the correct purpose of using ng-model..
The 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="username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="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.username="";$scope.password:"";
$scope.postForm = function() {
var encodedString = 'username=' +
encodeURIComponent($scope.username) +
'&password=' +
encodeURIComponent($scope.username);
$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';
})
}
}]);
After login test, i tried to go to the home page but i have a problem. I used $location.path("/templates/welcome.html");
but it does not work.
My controller in app.js is :
controller('SignInCtrl', function($scope, $state, $http) {
$scope.login = function(user) {
$http.get("http://localhost/app_dev.php/json/login/"+user.username+"/"+user.password)
.then(function(response){
console.log(response.data.status);
if(response.data.status === 200)
{
alert("redirect to main page");
$location.path("/templates/welcome.html");
}else if(response.data.status === 403){
alert("Login or password incorrect");
}else{
alert("User not found");
}
});
};
})
The alert is working but the redirection does not work. In the console i have this error :
ionic.bundle.js:25642 ReferenceError: $location is not defined
at app.js:37
Inject $location into the controller like this
controller('SignInCtrl', function($scope, $state, $http, $location) {
you have not injected $location service in your controller..
I think the probleme is coming from the statProrovider. My state is :
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signin', {
url: '/sign-in',
templateUrl: 'templates/welcome.html',
controller: 'SignInCtrl'
})
})
In my html page :
<div ng-controller="SignInCtrl">
<form novalidate class="simple-form">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="user.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="user.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="login(user)">Login</button>
</form>
I just started using Ionic that's why
So, I got an error today when I try to run Login function in Ionic.
The error said : TypeError: User.login is not a function (on controller.js
This is my controller.js :
angular.module('starter.controllers', [])
.controller('LoginCtrl', function($scope, User, $state) {
$scope.signIn = function(user) {
$scope.loginResult = User.login(user,
function(res) {
console.log('Login success');
console.log(res);
$state.go('tab.dash');
// success
}, function(res) {
// error
});
}
})
and this is my login.html :
<div class="list list-inset">
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="user.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="user.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="signIn(user)">Login</button>
This is my route in app.js :
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
Please correct my code.
Thanks for ur effort :)
Have you set up the loopback-sdk-angular properly? Please see my example at https://github.com/strongloop/loopback-getting-started-intermediate/blob/master/client/js/services/auth.js#L6-L15
I am new in angularJS. I write some code for navigation and it was work perfect. But it's stop working when I integrate MetroPreLoader in my angularJs service. It change browser URL but view does not update. if i remove MetroPreLoader from my service then it`s works again.
Here is my Code :
Service :
voiceAppControllers.factory('appService', function ($http, $log, $window) {
return {
showWaitBar : function() {
MetroPreLoader.setup({
logoUrl: "Content/Images/logo.png",
logoWidth: "100px",
logoHeight: "100px",
multipleBGColors: ["#CA3D3D", "#F58A16", "#32A237", "#A110E6"],
delay: "Unlimited"
});
MetroPreLoader.run();
},
hideWaitbar : function() {
MetroPreLoader.close();
}
};
})
Controller :
voiceAppControllers.controller('loginController', ['$scope', '$http', '$location', '$timeout', 'appService', 'notificationService',
function ($scope, $http, $location,$timeout, appService, notificationService) {
var onSuccess = function () {
notificationService.pushNotifaction("service update successfully.");
};
var onError = function () {
notificationService.pushNotifaction("service update fail.");
};
$scope.login = function () {
var credentials = "grant_type=password&username=" + $scope.loginModel.Username + "&password=" + $scope.loginModel.Password;
console.log(credentials);
appService.showWaitBar();
$http({
method: 'POST',
url: appService.loginUrl,
data: credentials,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function (data) {
console.log(data.access_token);
appService.updateAuthInfo(data.userName, data.access_token);
appService.hideWaitbar();
$location.path(appService.routes.dahboard);
})
.error(function () {
appService.clearAuthInfo();
appService.hideWaitbar();
$location.path(appService.routes.login);
notificationService.pushNotifaction("Login Fail. Wrong username and password.");
});
};
}
]);
when i comment appService.showWaitBar() and appService.hideWaitbar() then its works fine.
I defiantly miss something but don`t figure out that it is.
Thnaks.
Update 1:
my App.js is :
var voiceAppControllers = angular.module('voiceAppControllers', []);
var voiceApp = angular.module('voiceApp', ['ngRoute', 'voiceAppControllers', 'kendo.directives']);
voiceApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/organization', {
templateUrl: 'Templates/OrganizationTemplate.html',
controller: 'organizationController'
}).when('/service', {
templateUrl: 'Templates/ServiceTemplate.html',
controller: 'serviceController'
}).when('/login', {
templateUrl: 'Templates/LoginTemplate.html',
controller: 'serviceController'
}).when('/Dashboard', {
templateUrl: 'Templates/DashboardTemplate.html',
controller: 'dashboardController'
}).
otherwise({
redirectTo: '/login'
});
}]);
Login View is :
<div ng-controller="loginController">
<form name="loginFrom" novalidate ng-submit="login(loginFrom)">
<input type="hidden" ng-model="loginModel.Id" />
<h1>Login</h1>
<label>Need Some Text</label>
<div>
<label>username :</label>
<div class="input-control text">
<input type="text" placeholder="Your username" required ng-model="loginModel.Username" />
</div>
</div>
<div>
<label>password :</label>
<div class="input-control password">
<input type="password" placeholder="Your password" required ng-model="loginModel.Password" />
</div>
</div>
<div class="offset3">
<input class="primary" type="submit" value="UPDATE" ng-disabled="loginFrom.$invalid" />
</div>
</form>
</div>
my Dashboard View is :
<div ng-controller="dashboardController">
<h1>Dashboard</h1>
<input type="button" value="Next" />
</div>