Angular JS Multiple controller not working - javascript

Hello all i am doing a simple login and registration app. I am using two controllers one for login and one for sign up on same html page.The login is working not the registration.Where am i doing wrong.
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="UTF-8">
<title>WeBeR</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer- reset/2.0/reset.min.css">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css? family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font- awesome/4.3.0/css/font-awesome.min.css'>
<link rel="stylesheet" href="resources/css/style.css">
<link rel="stylesheet" href="resources/css/animate.css">
</head>
<body>
<div class="container">
<div class="top">
<h1 id="title" class="hidden"><span id="logo"><span><br><br><br><br> </span></span></h1>
</div>
<div class="login-box animated fadeInUp">
<div class="module form-module">
<div class="toggle">
<h3> SignUp</h3>
<i class="fa fa-times fa-pencil"></i>
<div class="tooltip">
Register
</div>
</div>
<div class="form" ng-controller="SignUpController as ctrl">
<h2>LogOn</h2>
<form name="ctrl.signupForm" ng-submit="ctrl.signup()">
<!-- *************************************USERNAME********************************************************************** -->
<div class="error" role="alert" ng-show="errorMsg"><strong>{{errorMsg}}</strong></div><br>
<div class="form-group" ng-class="{'has- error':ctrl.hasErrorClass('userName')}">
<input type="text" id="userName" name="userName" required placeholder="UserName"
ng-model="ctrl.newCustomer.userName" ng- model-options="{ updateOn : 'default blur' }"
ng-focus="ctrl.toggleUsernamePrompt(true)" ng-blur="ctrl.toggleUsernamePrompt(false)"/>
</div>
********************PASSWORD**********************************************************************
<div ng-class="{'has- error':ctrl.hasErrorClass('password')}">
<input type="password" id="password" required placeholder="Password"
type="{{ctrl.getPasswordType()}}"
ng-model-options="{ updateOn : 'default blur' }"
ng-model="ctrl.newCustomer.password"/>
</div>
<button type="submit">Sign In</button>
</form>
</div>
<!-- *************************************************REGISTRATION******************************************************** -->
<div class="form" ng-controller="RegistrationController as rctrl">
<h2>Create an account</h2>
<form name="rctrl.regForm" ng-submit="rctrl.register()">
<!-- *************************************************FIRSTNAME******************************************************** -->
<div class="form-group" ng-class="{'has-error':rctrl.hasErrorClass('firstName')}">
<input id="firstName" name="firstName" class="form-control" type="text" required placeholder="First Name"
ng-model="rctrl.newCustomer1.firstName" ng-model-options="{ updateOn : 'default blur' }"
ng-focus="rctrl.toggleFirstNamePrompt(true)" ng-blur="rctrl.toggleFirstNamePrompt(false)" />
</div>
<!-- *************************************************LASTNAME******************************************************** -->
<div class="form-group" ng-class="{'has-error':rctrl.hasErrorClass('lastName')}">
<input id="lastName" name="lastName" class="form-control" type="text" required placeholder="Last Name"
ng-model="rctrl.newCustomer1.lastName" ng-model-options="{ updateOn : 'default blur' }"
ng-focus="rctrl.toggleLastNamePrompt(true)" ng-blur="rctrl.toggleLastNamePrompt(false)"/>
</div>
<!-- *************************************************EMAIL******************************************************** -->
<div class="form-group" ng-class="{'has-error':rctrl.hasErrorClass('email')}">
<input id="email" name="email" class="form-control" type="email" required placeholder="E-mail"
ng-model="rctrl.newCustomer1.email" ng-model-options="{ updateOn : 'default blur' }"
ng-focus="rctrl.toggleEmailPrompt(true)" ng-blur="rctrl.toggleEmailPrompt(false)" email-available/>
<div class="message-animation" ng-if="rctrl.regForm.$pending.emailExists">checking....</div>
<div class="message-animation" ng-if="rctrl.regForm.$error.emailExists">Email exists.</div>
</div>
<!-- *************************************************USERNAME******************************************************** -->
<div class="form-group" ng-class="{'has-error':rctrl.hasErrorClass('userName')}">
<input id="userName" name="userName" class="form-control" type="text" required placeholder="UserName"
ng-model="rctrl.newCustomer1.userName" ng-model-options="{ updateOn : 'default blur' }"
ng-focus="rctrl.toggleUsernamePrompt(true)" ng-blur="rctrl.toggleUsernamePrompt(false)" user-available/>
<div class="message-animation" ng-if="rctrl.regForm.$pending.userExists">checking....</div>
<div class="message-animation" ng-if="rctrl.regForm.$error.userExists">UserName exists already.</div>
</div>
<!-- *************************************************PASSWORD******************************************************** -->
<div class="form-group">
<div class="input-group" ng-class="{'has-error':rctrl.hasErrorClass('password')}">
<input id="password" name="password" class="form-control" required placeholder="Password"
type="{{rctrl.getPasswordType()}}"
ng-model-options="{ updateOn : 'default blur' }"
ng-model="rctrl.newCustomer1.password"
/>
</div>
</div>
<button>Register</button>
</form>
</div>
<div class="cta">
</div>
</div>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script>
<script src="resources/js/register.js"></script>
<script src="resources/js/animate.js"></script>
<script src="resources/js/login.js"></script>
</body>
</html>
My JS
angular.module('MyApp', [])
.controller('SignUpController',function($scope, $http) {
var ctrl = this, newCustomer = {
userName : '',
password : ''
};
var signup = function() {
if (ctrl.signupForm.$valid) {
ctrl.showSubmittedPrompt = true;
submitForm();
clearForm();
}
};
var register = function() {
if (ctrl.signupForm.$valid) {
ctrl.showSubmittedPrompt = true;
alert("success");
}
};
var clearForm = function() {
ctrl.newCustomer = {
userName : '',
password : ''
};
ctrl.signupForm.$setUntouched();
ctrl.signupForm.$setPristine();
};
var submitForm = function(userName, password) {
$http({
method : 'POST',
url : 'http://localhost:8081/Classmate/user/getvalid',
data : {
'userName' : $scope.ctrl.newCustomer.userName,
'password' : $scope.ctrl.newCustomer.password
},
headers : {
'Content-Type' : 'application/json'
}
}).success(function(data, status, headers, config) {
console.log(data);
if (data == false) {
var path = "/Classmate/view.jsp";
window.location.href = path;
} else {
$scope.errorMsg = "Invalid Credentials";
}
}).error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit.Please try after sometime.';
})
};
var getPasswordType = function() {
return ctrl.signupForm.showPassword ? 'text' : 'password';
};
var toggleUsernamePrompt = function(value) {
ctrl.showUsernamePrompt = value;
};
var hasErrorClass = function(field) {
return ctrl.signupForm[field].$touched
&& ctrl.signupForm[field].$invalid;
};
var showMessages = function(field) {
return ctrl.signupForm[field].$touched
|| ctrl.signupForm.$submitted
};
ctrl.showUsernamePrompt = false;
ctrl.showSubmittedPrompt = false;
ctrl.toggleUsernamePrompt = toggleUsernamePrompt;
ctrl.getPasswordType = getPasswordType;
ctrl.hasErrorClass = hasErrorClass;
ctrl.showMessages = showMessages;
ctrl.newCustomer = newCustomer;
ctrl.signup = signup;
ctrl.clearForm = clearForm;
})
/*********************************************REG CONTROLLER*******************************************************/
.controller('RegisterController', function($scope, $http) {
var rctrl = this, newCustomer1 = {
firstName : '',
lastName : '',
email : '',
zipName : '',
userName : '',
password : ''
};
var register = function() {
if (rctrl.regForm.$valid) {
rctrl.showSubmittedPrompt = true;
submitRegForm();
clearForm();
}
};
var clearForm = function() {
rctrl.newCustomer1 = {
firstName : '',
lastName : '',
email : '',
userName : '',
password : ''
};
rctrl.regForm.$setUntouched();
rctrl.regForm.$setPristine();
};
var submitRegForm = function() {
var formData = {
'firstName' : $scope.rctrl.newCustomer1.firstName,
'lastName' : $scope.rctrl.newCustomer1.lastName,
'email' : $scope.rctrl.newCustomer1.email,
'userName' : $scope.rctrl.newCustomer1.userName,
'password' : $scope.rctrl.newCustomer1.password
}
var response = $http.post(
'http://localhost:8081/Classmate/user/save', formData);
response.success(function(data, status, headers, config) {
/*
* alert( "Congrats,"+JSON.stringify(data.firstName)+"
* Welcome aboard.");
*/
var path = "/Classmate/sample.jsp";
window.location.href = path;
});
response.error(function(data, status, headers, config) {
alert("Error Details1: " + JSON.stringify({
data : data
}));
});
};
var getPasswordType = function() {
return rctrl.regForm.showPassword ? 'text' : 'password';
};
var toggleEmailPrompt = function(value) {
rctrl.showEmailPrompt = value;
};
var toggleUsernamePrompt = function(value) {
rctrl.showUsernamePrompt = value;
};
var toggleFirstNamePrompt = function(value) {
rctrl.showFirstNamePrompt = value;
};
var toggleLastNamePrompt = function(value) {
rctrl.showLastNamePrompt = value;
};
var hasErrorClass = function(field) {
return rctrl.regForm[field].$touched
&& rctrl.regForm[field].$invalid;
};
var showMessages = function(field) {
return rctrl.regForm[field].$touched
|| rctrl.regForm.$submitted
};
rctrl.showLastNamePrompt = false;
rctrl.showFirstNamePrompt = false;
rctrl.showEmailPrompt = false;
rctrl.showUsernamePrompt = false;
rctrl.showSubmittedPrompt = false;
rctrl.toggleEmailPrompt = toggleEmailPrompt;
rctrl.toggleUsernamePrompt = toggleUsernamePrompt;
rctrl.toggleFirstNamePrompt = toggleFirstNamePrompt;
rctrl.toggleLastNamePrompt = toggleLastNamePrompt;
rctrl.getPasswordType = getPasswordType;
rctrl.hasErrorClass = hasErrorClass;
rctrl.showMessages = showMessages;
rctrl.newCustomer1 = newCustomer1;
rctrl.register = register;
rctrl.clearForm = clearForm;
})
.directive(
'emailAvailable',
function($timeout, $q, $http) {
return {
restrict : 'AE',
require : 'ngModel',
link : function(scope, elm, attr, model) {
model.$asyncValidators.emailExists = function(email) {
return $http.get(
'http://localhost:8081/Weber/user/getemail? email='
+ email).then(function(res) {
+$timeout(function() {
model.$setValidity('emailExists', res.data);
console.log(res.data);
}, 1000);
});
};
}
}
})
.directive(
'userAvailable',
function($timeout, $q, $http) {
return {
restrict : 'AE',
require : 'ngModel',
link : function(scope, elm, attr, model) {
model.$asyncValidators.userExists = function(userName) {
return $http.get(
'http://localhost:8081/Weber/user/checkuser?user='
+ userName).then(function(res) {
+$timeout(function() {
model.$setValidity('userExists', res.data);
console.log(res.data);
}, 1000);
});
};
}
}
});
When i try to click on register it doesn't hit the controller
Thank you
Mark

You have your controller misnamed. You call it RegisterController in your controller js file but declare it as RegistrationController in your ng-Controller directive.

Related

$http.put request changing into OPTIONS request in AngularJS 1.3.15 [duplicate]

This question already has answers here:
Angular $http is sending OPTIONS instead of PUT/POST
(2 answers)
Closed 5 years ago.
I'm new to the AngularJS. I'm using AngularJS 1.3.15 version. When I try to call an api with PUT method, It's generating OPTIONS request. I don't know where I'm doing mistake. I tried so many methods which is suggested in Stockoverflow, but still I'm not getting anything. Please help me to resolve this issue. below are my Controller, Models, html files and Chrome developer tool network activity screenshot.
Controller file users.js
'use strict';
mmlApp_users.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/users/update/:userId', {
templateUrl: 'views/users/update.html',
controller: 'update',
resolve: {
user: function(users, $route){
var userId = $route.current.params.userId
return users.getUser(userId);
}
}
})
.otherwise({
redirectTo: '/users/index'
});
}]);
Model file - users.js
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route', function($http, $location, $route){
var obj = {};
obj.getUser = function(userId){
return $http.get(serviceBase + 'users/view/'+userId);
};
obj.updateUser = function(user){
var config = {
headers: {
'Content-Type': 'application/json'
}
};
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
$http.put(serviceBase + 'users/update/'+user.id+'?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13', userParams, config)
.then(successHandler).catch(errorHandler);
function successHandler(){
$location.path('/users/index');
}
function errorHandler(){
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
Views - update.html
<div>
<h1>{{title}}</h1>
<p>{{ message}}</p>
<form role="form" name="myForm">
<div class="row">
<div class= "form-group col-md-6" ng-class="{error: myForm.first_name.$invalid}">
<label> First Name: </label>
<div>
<input name="first_name" ng-model="user.first_name" type= "text" class= "form-control" placeholder="First Name" required/>
<span ng-show="myForm.first_name.$dirty && myForm.first_name.$invalid" class="help-inline">First Name Required</span>
</div>
</div>
<div class= "form-group col-md-6" ng-class="{error: myForm.last_name.$invalid}">
<label> Last Name: </label>
<div>
<input name="last_name" ng-model="user.last_name" type= "text" class= "form-control" placeholder="Last Name" required/>
<span ng-show="myForm.last_name.$dirty && myForm.last_name.$invalid" class="help-inline">Last Name Required</span>
</div>
</div>
</div>
....
....
....
Cancel
<button ng-click="updateUser(user);" ng-disabled="myForm.$invalid" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
In chrome developer tool network activity screenshot -
try in your factory:
(function () {
'use strict';
mmlApp_users.factory('users', ['$http', '$location', '$route','$httpParamSerializer',
function ($http, $location, $route, $httpParamSerializer) {
var obj = {};
obj.getUser = function (userId) {
return $http.get(serviceBase + 'users/view/' + userId);
};
obj.updateUser = function (user) {
var userParams = {
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password,
address: user.address,
state: user.state,
city: user.city,
zip_code: user.zip_code
};
var req = {
method: 'PUT',
url: serviceBase + 'users/update/' + user.id + '?access-token=8e0bb9b3-b35f-4d30-943d-6028c0b85c13',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: $httpParamSerializer(userParams)
};
$http(req)
.then(successHandler)
.catch(errorHandler);
function successHandler() {
$location.path('/users/index');
}
function errorHandler() {
alert('Oops! Somthing went wrong.');
//$location.path('/users/create');
}
};
return obj;
}]);
})();
And Goog Lock :)

Failed to instantiate module angularApp due to

I have this bug when I work authentification between angular js and symfony , I have bug in front end (angular js) :
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=angularApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.5%2F%24injector%2Fmodulerr%3Fp0%3Drestangular%26p1%3DTypeError%253A%2520Cannot%2520read%2520property%2520'isUndefined'%2520of%2520undefined%250A%2520%2520%2520%2520at%2520Object.Configurer.init%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A42%253A29)%250A%2520%2520%2520%2520at%2520new%2520%253Canonymous%253E%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A812%253A16)%250A%2520%2520%2520%2520at%2520Object.instantiate%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A44%253A458)%250A%2520%2520%2520%2520at%2520c%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A370)%250A%2520%2520%2520%2520at%2520Object.provider%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A312)%250A%2520%2520%2520%2520at%2520d%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A237)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A358%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A322%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20gb%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A46%3A251)%0A%20%20%20%20at%20c%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A332)
and this is link error:
https://docs.angularjs.org/error/$injector/unpr?p0=RestangularProvider%20%3C-%20Restangular%20%3C-%20MainCtrl
code index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="styles/main.css"> -->
</head>
<body ng-app="angularApp">
<div class="container">
<div ng-include="'main.html" ng-controller="MainCtrl"></div>
<div ui-view></div>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
--> <script src="../node_modules/angular/angular.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.js"></script>
-->
<script src="../node_modules/restangular/dist/restangular.js"></script>
<script src="../node_modules/lodash/lodash.js"></script>
<script src="app.js"></script>
<script src="main.js"></script>
</body>
</html>
code main.html:
<!—Displays error or success messages-->
<span>{{message}}</span><br><br>
<!—Login/logout form-->
<form ng-show="!isAuthenticated" ng-submit="submit()">
<label>Login Form:</label><br>
<input ng-model="user.username" type="text" name="user" placeholder="Username" disabled="true" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" disabled="true" />
<input type="submit" value="Login" />
</form>
<div ng-show="isAuthenticated">
<a ng-click="logout()" href="">Logout</a>
</div>
<div ui-view ng-show="isAuthenticated"></div>
<br><br>
<!—Displays contacts list-->
<h1 ng-show="isAuthenticated">Liste des Contacts</h1>
<article ng-repeat="contact in contacts" ng-show="isAuthenticated" id="{{ contact['#id'] }}" class="row marketing">
<h2>{{ contact.nom }}</h2>
<!—Displays contact phones list-->
<h3 ng-repeat="moyenComm in contact.moyensComm">Tél : {{ moyenComm.numero }}</h3>
</article><hr>
<!—Create contact form-->
<form name="createContactForm" ng-submit="createContact(createContactForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau contact</h2>
<!—Displays error / success message on creating contact-->
<div ng-show="contactSuccess" class="alert alert-success" role="alert">Contact publié.</div>
<div ng-show="contactErrorTitle" class="alert alert-danger" role="alert">
<b>{{ contactErrorTitle }}</b><br>
{{ contactErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newContact.nom" placeholder="Nom" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!—Phone form-->
<form name="createPhoneForm" ng-submit="createPhone(createPhoneForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau téléphone</h2>
<div ng-show="phoneSuccess" class="alert alert-success" role="alert">Téléphone publié.</div>
<div ng-show="phoneErrorTitle" class="alert alert-danger" role="alert">
<b>{{ phoneErrorTitle }}</b><br>
{{ phoneErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newPhone.numero" placeholder="Numéro" class="form-control">
</div>
<div class="form-group">
<label for="contact">Contact</label>
<!—SelectBox de liste de contacts-->
<select ng-model="newPhone.contact" ng-options="contact['#id'] as contact.nom for contact in contacts" id="contact"></select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
code app.js:
'use strict';
var app = angular
.module('angularApp', ['restangular'])
app.config(['RestangularProvider', function (RestangularProvider) {
// URL ENDPOINT TO SET HERE !!!
RestangularProvider.setBaseUrl('http://your_vhost/api');
RestangularProvider.setRestangularFields({
id: '#id'
});
RestangularProvider.setSelfLinkAbsoluteUrl(false);
RestangularProvider.addResponseInterceptor(function (data, operation) {
function populateHref(data) {
if (data['#id']) {
data.href = data['#id'].substring(1);
}
}
populateHref(data);
if ('getList' === operation) {
var collectionResponse = data['hydra:member'];
collectionResponse.metadata = {};
angular.forEach(data, function (value, key) {
if ('hydra:member' !== key) {
collectionResponse.metadata[key] = value;
}
});
angular.forEach(collectionResponse, function (value) {
populateHref(value);
});
return collectionResponse;
}
return data;
});
}])
;
code main.js:
'use strict';
var app = angular
.module('angularApp')
app.controller('MainCtrl', function ($scope, $http, $window, Restangular) {
// fosuser user
$scope.user = {username: 'johndoe', password: 'test'};
// var to display login success or related error
$scope.message = '';
// In my example, we got contacts and phones
var contactApi = Restangular.all('contacts');
var phoneApi = Restangular.all('telephones');
// This function is launched when page is loaded or after login
function loadContacts() {
// get Contacts
contactApi.getList().then(function (contacts) {
$scope.contacts = contacts;
});
// get Phones (throught abstrat CommunicationWays alias moyensComm)
phoneApi.getList().then(function (phone) {
$scope.phone = phone;
});
// some vars set to default values
$scope.newContact = {};
$scope.newPhone = {};
$scope.contactSuccess = false;
$scope.phoneSuccess = false;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
// contactForm handling
$scope.createContact = function (form) {
contactApi.post($scope.newContact).then(function () {
// load contacts & phones when a contact is added
loadContacts();
// show success message
$scope.contactSuccess = true;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
// re-init contact form
$scope.newContact = {};
form.$setPristine();
// manage error handling
}, function (response) {
$scope.contactSuccess = false;
$scope.contactErrorTitle = response.data['hydra:title'];
$scope.contactErrorDescription = response.data['hydra:description'];
});
};
// Exactly same thing as above, but for phones
$scope.createPhone = function (form) {
phoneApi.post($scope.newPhone).then(function () {
loadContacts();
$scope.phoneSuccess = true;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
$scope.newPhone = {};
form.$setPristine();
}, function (response) {
$scope.phoneSuccess = false;
$scope.phoneErrorTitle = response.data['hydra:title'];
$scope.phoneErrorDescription = response.data['hydra:description'];
});
};
}
// if a token exists in sessionStorage, we are authenticated !
if ($window.sessionStorage.token) {
$scope.isAuthenticated = true;
loadContacts();
}
// login form management
$scope.submit = function() {
// login check url to get token
$http({
method: 'POST',
url: 'http://your_vhost/login_check',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param($scope.user)
// with success, we store token to sessionStorage
}).success(function(data) {
$window.sessionStorage.token = data.token;
$scope.message = 'Successful Authentication!';
$scope.isAuthenticated = true;
// ... and we load data
loadContacts();
// with error(s), we update message
}).error(function() {
$scope.message = 'Error: Invalid credentials';
delete $window.sessionStorage.token;
$scope.isAuthenticated = false;
});
};
// logout management
$scope.logout = function () {
$scope.message = '';
$scope.isAuthenticated = false;
delete $window.sessionStorage.token;
};
// This factory intercepts every request and put token on headers
})
app.factory('authInterceptor', function($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// if 401 unauthenticated
}
return response || $q.when(response);
}
};
// call the factory ...
})
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
help me please for resolve this bug and thanks advanced
I think isUndefined is a function in underscore.js, which is a dependency of Restangular:
http://underscorejs.org/#isUndefined
Do you have underscore.js included in your assets?

Laravel and Angular js file upload

How I can save images with laravel and angular js ?
are more inputs , but that work for me , are of type text
My index:
<div class="container" ng-app="todoApp" ng-controller="todoController">
<h1>Profile</h1>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Foto de perfil: </h4>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type='File' name="photo" ng-model="todo.photo" class="image-upload"required/>
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="">Nombre del bar: </label>
<input type='text' ng-model="todo.name" class="form-control" required/>
</div>
<button class="btn btn-primary btn-block" ng-click="addTodo()">Guardar</button>
<i ng-show="loading" class="fa fa-spinner fa-spin"></i>
</div>
</div>
My route:
Route::get('admin/bar', 'BarsController#index');
Route::resource('/bar', 'BarController');
My model:
namespace App;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Model;
class bar extends Model
{
protected $fillable = array('name','photo', 'cover',
'description', 'phone', 'email','direction', );
public function setPhotoAttribute($photo)
{
$file = array('image' => Input::file('photo'));
$destinationPath = 'images/bar/profile';
$extension = Input::file('photo')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$this->attributes['photo'] = $fileName;
Input::file('photo')->move($destinationPath, $fileName);
}
BarsController:
public function index()
{
return view ('bar.index');
}
BarController:
public function store() {
$todo = \Auth::user()->bars()->create(Request::all());
return $todo;
}
App.js ( Angular JS ):
var app = angular.module('todoApp', function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
// Todo Controller ,...
app.controller('todoController', function($scope, $http) {
$scope.todos = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/bar').
success(function(data, status, headers, config) {
$scope.todos = data;
$scope.loading = false;
});
}
$scope.addTodo = function() {
$scope.loading = true;
$http.post('/bar', {
name: $scope.todo.name,
description: $scope.todo.description,
phone: $scope.todo.phone,
email: $scope.todo.email,
direction: $scope.todo.direction,
photo: $scope.todo.photo,
cover: $scope.todo.cover
}).success(function(data, status, headers, config) {
$scope.todos.push(data);
$scope.todo = '';
$scope.loading = false;
});
};
$scope.updateTodo = function(todo) {
$scope.loading = true;
$http.put('/bar' + todo.id, {
title: todo.title,
done: todo.done
}).success(function(data, status, headers, config) {
todo = data;
$scope.loading = false;
});;
};
$scope.deleteTodo = function(index) {
$scope.loading = true;
var todo = $scope.todos[index];
$http.delete('/bar' + todo.id)
.success(function() {
$scope.todos.splice(index, 1);
$scope.loading = false;
});;
};
$scope.init();
});
I am using below code to upload image try this, I hope it works for you too.
<-- Front end file input -->
<input type="file" name="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
<-- Angular Controller's File -->
$scope.uploadavtar = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/uploadavtar", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).then(function successCallback(response) {
alert(response);
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
alert(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
<-- In Route File -->
Route::post('/uploadavtar', 'UsersController#uploadavtar');
<-- In UsersController -->
public function uploadavtar(Request $request){
$user = JWTAuth::parseToken()->authenticate();
$user_id = $user->id;
$user_name = $user->first_name." ".$user->last_name;
$file = array('image' => Input::file('file'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return "validation failed";
}else {
// checking file is valid.
if (Input::file('file')->isValid()) {
$destinationPath = 'assets/img'; // upload path
$extension = Input::file('file')->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
Input::file('file')->move($destinationPath, $user_name."_$user_id".".jpeg"); // uploading file to given path
// sending back with message
return 'Upload successfully';
}
else {
// sending back with error message.
return 'uploaded file is not valid';
}
}
}

Modify method to show success/failed Message. AngularJS

I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.
you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate

Error occurs on Submit: TypeError: dataService.Login is not a function

Error happens when I click the submit button on a form.
LoginController and controllerAs is define in route config
Angular version: AngularJS v1.3.11
dataService.js file
'use strict';
app.factory('dataService',['$http',DataService]);
function DataService($http) {
var urlBase='http://washerycloud.cloudapp.net/v1/user/';
var service = {};
service.Login =Login;
service.Register= Register;
service.Store = StoreID;
service.Update = Update;
service.Delete = Delete;
return service;
/**Login function*/
function Login(user) {
return $http.get(urlBase + 'login',{params: {name: user.name, password: user.password}}).
then(handleSuccess, handleError('Error login'));
}
/**Register function*/
function Register(user) {
return $http.get(urlBase + 'create',
{params: { name: user.name, surname: user.surname, telephone: user.telephone,
email: user.email, username: user.username, password: user.password }})
.then(handleSuccess, handleError('Error register user'));
}
// private functions
function handleSuccess(data) {
return data;
}
function handleError(error) {
return function () {
return { success: false, message: error };
};
}
}
LoginController.js File
'use strict';
// login controller
app.controller('LoginController',
[ '$state','$window','dataService',
Register]);
function Register( $state, dataService, $window) {
var vm=this;
vm.user = {};
vm.authError = null;
vm.login = function() {
vm.authError = null;
// Try to login
dataService.Login(vm.user)
.then(function(response) {
if ( !response.data.user ) {
vm.authError = 'Email or Password not right';
$window.alert(response);
}else{
// $state.go('app.dashboard-v1');
$window.alert(response);
}
}, function(x) {
vm.authError = 'Server Error';
});
};
};
--------------------------------------------------------------------
login.html
<form name="form" class="form-validation">
<div class="text-danger wrapper text-center" ng-show="authError">
{{authError}}
</div>
<div class="list-group list-group-sm">
<div class="list-group-item">
<input placeholder="Name" class="form-control no-border" ng-model="vm.user.name" required>
</div>
<div class="list-group-item">
<input type="password" placeholder="Password" class="form-control no-border" ng-model="vm.user.password" required>
</div>
</div>
<button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="login()" ng-disabled='form.$invalid'>Log in</button>
<div class="text-center m-t m-b"><a ui-sref="access.forgotpwd">Password dimenticata?</a></div>
<div class="line line-dashed"></div>
<p class="text-center"><small>Non hai un account?</small></p>
<a ui-sref="access.signup" class="btn btn-lg btn-default btn-block">Registrati !</a>
</form>
----------------------------------------------------------------------------
ERROR MESSAGE
TypeError: dataService.Login is not a function
at Register.vm.login (login.js:17)
at $parseFunctionCall (angular.js:12336)
at angular-touch.js:472
at Scope.$get.Scope.$eval (angular.js:14388)
at Scope.$get.Scope.$apply (angular.js:14487)
at HTMLButtonElement.<anonymous> (angular-touch.js:471)
at HTMLButtonElement.n.event.dispatch (jquery.js:4430)
at HTMLButtonElement.n.event.add.r.handle (jquery.js:4116)
The order in which you inject the services needs to be the same in both the array annotation and the parameter list for your controller function.
Change your controller declaration so the order of injected services line up...
app.controller('LoginController', [
'$state','$window','dataService',Register]);
function Register( $state, $window, dataService) {
...

Categories

Resources