Failed to instantiate module angularApp due to - javascript

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?

Related

Angular JS Multiple controller not working

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.

How to route CodeIgniter with Angular.js? [duplicate]

This question already has an answer here:
AngularJS and Codeigniter - Combination & Data Transfer
(1 answer)
Closed 6 years ago.
I'm trying to use Angular.js and CodeIgniter together.
With ngRoute in my app, I'm setting in my main.js:
$locationProvider.html5Mode(true);
$routeProvider.when('/test', {
templateUrl: 'partials/test.html'
});
$routeProvider.otherwise({
templateUrl: 'partials/home.html'
});
In my routes.php, I'm setting:
$route['default_controller'] = 'home';
$route['(:any)'] = "home";
And in my home/index.php, I have the <ng-view></ng-view>.
The thing is, without the html5Mode(true) (with /#/ on the URL) everything works fine. But otherwise, the partials file works, but the page reloads anyway.
In Inspector Elements, things look like this:
partials/test.html loaded, but the page realoded, and the error "ngView: undefined" showed up.
I'm still learning Angularjs. Anyone can help?
this is a production form (i´m using htaccess)
in the js folder create a app.js
js/app.js
//create app module
var app = angular.module("app", []);
//login configuration
app.config(function($routeProvider){
$routeProvider.when("/login", {
controller : "loginController",
templateUrl : "templates/login.html"
})
.when("/home", {
controller : "homeController",
templateUrl : "templates/home.html"
})
});
js/controllers/controllers.js
//save & delete sessions
app.factory("sesionesControl", function(){
return {
//obtenemos una sesión //getter
get : function(key) {
return sessionStorage.getItem(key)
},
//creamos una sesión //setter
set : function(key, val) {
return sessionStorage.setItem(key, val)
},
//limpiamos una sesión
unset : function(key) {
return sessionStorage.removeItem(key)
}
}
})
//simple message in bad login
app.factory("mensajesFlash", function($rootScope){
return {
show : function(message){
$rootScope.flash = message;
},
clear : function(){
$rootScope.flash = "";
}
}
});
//angular login & logout
app.factory("authUsers", function($http, $location, sesionesControl, mensajesFlash){
var cacheSession = function(email){
sesionesControl.set("userLogin", true);
sesionesControl.set("email", email);
}
var unCacheSession = function(){
sesionesControl.unset("userLogin");
sesionesControl.unset("email");
}
return {
//return authUsers
login : function(user){
return $http({
url: 'http://localhost/login_ci_angularjs/login/loginUser',
method: "POST",
data : "email="+user.email+"&password="+user.password,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
if(data.respuesta == "success"){
//if true clear flash messages
mensajesFlash.clear();
//create session with email
cacheSession(user.email);
//redirect to home
$location.path("/home");
}else if(data.respuesta == "incomplete_form"){
mensajesFlash.show("The email & user are required");
}else if(data.respuesta == "failed"){
mensajesFlash.show("The email ore password are wrong");
}
}).error(function(){
$location.path("/")
})
},
//close session
logout : function(){
return $http({
url : "http://localhost/login_ci_angularjs/login/logoutUser"
}).success(function(){
//delete session in sessionStorage
unCacheSession();
$location.path("/login");
});
}
}
})
app.controller("homeController", function($scope, sesionesControl, authUsers){
$scope.email = sesionesControl.get("email");
$scope.logout = function(){
authUsers.logout();
}
})
//permisos
app.run(function($rootScope, $location, authUsers){
//url that the user can access
var rutasPrivadas = ["/home","/info","/login"];
$rootScope.$on('$routeChangeStart', function(){
if(in_array($location.path(),rutasPrivadas) && !authUsers.isLoggedIn()){
$location.path("/login");
}
//if user go to login (if the session exist redirect to home)
if(($location.path() === '/login') && authUsers.isLoggedIn()){
$location.path("/home");
}
})
})
//controller loginController
app.controller("loginController", function($scope, $location, authUsers){
$scope.user = { email : "", password : "" }
authUsers.flash = "";
//submit form
$scope.login = function(){
authUsers.login($scope.user);
}
})
//if user has permissions in the url
function in_array(needle, haystack, argStrict){
var key = '',
strict = !! argStrict;
if(strict){
for(key in haystack){
if(haystack[key] === needle){
return true;
}
}
}else{
for(key in haystack){
if(haystack[key] == needle){
return true;
}
}
}
return false;
}
templates/login.htm
<form name="loginUserForm">
<fieldset>
<legend>form login</legend>
<div class="row">
<div ng-show="flash">
<div data-alert class="alert-box alert round">{{ flash }}</div>
</div>
<div class="large-12 columns">
<label>Email</label>
<input type="email" required placeholder="mail#mail.com" ng-model="user.email">
</div>
<div class="large-12 columns">
<label>Password</label>
<input type="password" required placeholder="Password" ng-model="user.password">
</div>
<button type="submit" ng-disabled="!loginUserForm.$valid" ng-click="login(user)" class="button expand round">Login</button>
</div>
</fieldset>
</form>
Login.php controller
class Login extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->view("login");
}
//called from angular controller.js
public function loginUser(){
if($this->input->post("email") && $this->input->post("password"))
{
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
if($this->form_validation->run() == false){
echo json_encode(array("respuesta" => "incomplete_form"));
}else{
$this->load->model("login_model");
$email = $this->input->post("email");
$password = $this->input->post("password");
$loginUser = $this->login_model->loginUser($email,$password);
if($loginUser === true){
echo json_encode(array("respuesta" => "success"));
}else{
echo json_encode(array("respuesta" => "failed"));
}
}
}else{
echo json_encode(array("respuesta" => "incomplete_form"));
}
}
public function logoutUser(){
$this->session->sess_destroy();
}
}
apllications/views/login.php
<!DOCTYPE html>
<html lang="es" ng-app="app">
<head>
<meta charset="UTF-8" />
<title>CI & Angular</title>
</head>
<body>
<!-- with this ng-view, we load all views -->
<div class="row" ng-view></div>
<script type="text/javascript" src="<?php echo base_url() ?>js/angular.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/app.js"></script>
<script type="text/javascript" src="<?php echo base_url() ?>js/controllers/controllers.js"></script>
</body>
</html>
templates/home.html
<h3 class="subheader">Hello {{ email }}</h3>
<button ng-click="logout()" class="large-12 button expand">Logout</button>

Angularjs Uncaught Error: [$injector:modulerr]

This issues seems like a very common one. But I have been unsuccessful to find the issue for a long time now. I have distributed the application, controller,service modules into separate js files as below.
app.js
/** Main AngularJS Web Application */
var app = angular.module('ngdemo', [ 'ngdemo.controllers', 'ngdemo.services' ]);
app
.config([
'$routeProvider',
'$httpProvider',
function($routeProvider, $httpProvider) {
$routeProvider.when('/documents', {
templateUrl : 'documents.html',
controller : 'documentListCtrl'
}).when('/documents/:id', {
templateUrl : 'edit_document.html',
controller : 'documentDetailCtrl'
}).when('/document', {
templateUrl : 'create_document.html',
controller : 'documentCreationCtrl'
}).otherwise({
redirectTo : '/home'
});
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
} ]);
and document_controllers.js
var controllers = angular.module('ngdemo.controllers', []);
/* ... */
controllers.controller( 'navigation', ['$rootScope', '$scope', '$http', '$location', '$route', function($rootScope, $scope, $http, $location, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
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($rootScope.authenticated);
}).error(function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/documents");
$scope.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/home");
$scope.error = true;
$rootScope.authenticated = false;
}
})
};
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}]);
/* ... */
controllers.controller('documentListCtrl', ['$scope', 'DocumentsFactory', 'DocumentFactory', '$location',
function ($scope, DocumentsFactory, DocumentFactory, $location) {
// callback for ng-click 'editDocument':
$scope.editDocument = function (documentId) {
$location.path('/documents/' + documentId);
};
// callback for ng-click 'deleteDocument':
$scope.deleteDocument = function (userId) {
DocumentFactory.delete({ id: userId });
$scope.documents = DocumentsFactory.query();
};
// callback for ng-click 'createDocument':
$scope.createNewDocument = function () {
$location.path('/document');
};
$scope.documents = DocumentsFactory.query();
}]);
/* ... */
controllers.controller('documentDetailCtrl', ['$scope', '$routeParams', 'DocumentFactory', '$location',
function ($scope, $routeParams, DocumentFactory, $location) {
// callback for ng-click 'updateDocument':
$scope.updateDocument = function () {
DocumentFactory.update($scope.document);
$location.path('/documents');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/documents');
};
$scope.document = DocumentFactory.show({id: $routeParams.id});
}]);
/* ... */
controllers.controller('documentCreationCtrl', ['$scope', 'DocumentsFactory', '$location',
function ($scope, DocumentsFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewDocument = function () {
DocumentsFactory.create($scope.document);
$location.path('/documents');
}
}]);
and finally document_services.js
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('DocumentsFactory', function ($resource) {
return $resource('/rest/documents', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
services.factory('DocumentFactory', function ($resource) {
return $resource('/rest/documents/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
})
});
In my index.html file,
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Sample Project</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/jumbotron.css" rel="stylesheet">
</head>
<body ng-app="ngdemo" class="ng-cloak">
<nav class="navbar navbar-inverse navbar-fixed-top">
<!-- ng-controller="navigation" -->
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ng-class="{active:tab('home')}">Home</li>
<li ng-show="authenticated" ng-class="{active:tab('document')}">Document</li>
</ul>
<form ng-show="!authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" id="username"
name="username" ng-model="credentials.username" />
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" ng-model="credentials.password" />
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
<div ng-show="authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<button type="submit" class="btn btn-success" ng-click="logout()">Log
Out</button>
</div>
</div>
</div>
</nav>
<div ng-view class="container"></div>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/app.js"></script>
<script src="js/document_controllers.js"></script>
<script src="js/document_services.js"></script>
</body>
</html>
In my project I am using wro4j-maven-plugin to generate javaScript files
<groups xmlns="http://www.isdc.ro/wro">
<group name="angular-bootstrap">
<css>webjar:bootstrap/3.2.0/less/bootstrap.less</css>
<css>file:${project.basedir}/src/main/wro/main.less</css>
<js>webjar:jquery/2.1.1/jquery.min.js</js>
<js>webjar:angularjs/1.3.8/angular.min.js</js>
<js>webjar:angularjs/1.3.8/angular-route.min.js</js>
<js>webjar:angularjs/1.3.8/angular-cookies.min.js</js>
</group>
</groups>
So, this generated angular-bootstrapfile is properly referenced in the html file, but still the loading of modules seems to be failing. Any help is immensely appreciated.
Thanks
You probably need to install the route provider and include ngRoute dependancy in your app.js.
Here is the documentation: $routeProvider
And about the installation: ngRoute

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) {
...

JSON request with Angular Displays an Empty Response

I believe Angular is loading the page before it receives all the information from JSONP. If I refresh the page a couple of times I do get the information to display; however, it is not constant. My code is almost the same as the code I am using on my projects page which does not have the same issue.
HTML:
<div class="container">
<div class="row push-top" ng-show="user">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">
<div class="well well-sm">
<div class="row">
<div class="col-sm-3 col-md-2">
<img ng-src="[[ user.images.138 ]]" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-7 col-md-8">
<h4 ng-bind="user.display_name"></h4>
<h5 ng-bind="user.occupation"></h5>
<i class="fa fa-map-marker"></i>
<cite title="[[ user.city ]], [[ user.country ]]">[[ user.city ]], [[ user.country ]]</cite>
<br>
<strong ng-bind="user.stats.followers"></strong> Followers, <strong ng-bind="user.stats.following"></strong> Following
<hr>
<p style="margin-top:10px;" ng-bind="user.sections['About Me']"></p>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScipt:
'use strict';
angular.module('angularApp')
.controller('AboutCtrl', function ($scope, $window, Behance) {
$scope.loading = true;
Behance.getUser('zachjanice').then(function (user) {
$scope.user = user;
$scope.loading = false;
}, function (error) {
console.log(error);
$scope.loading = false;
$scope.user = null;
});
$scope.gotoUrl = function (url) {
$window.location.href = url;
};
});
You can see the page in question at: http://zachjanice.com/index.html#/about. Thanks in Advance.
As requested here is the behance service:
'use strict';
angular.module('angularApp')
.factory('Behance', function ($http, $q, localStorageService, BEHANCE_CLIENT_ID) {
// Should be called to refresh data (for testing purposes)
// localStorageService.clearAll();
// Public API
return {
// Get a list of projects
getProjects: function (config) {
var pageNum = 1;
if (angular.isObject(config) && angular.isDefined(config.page)) {
pageNum = config.page;
}
var _projects = $q.defer(),
_storedProjects = localStorageService.get('Projects_Page_');
if (_storedProjects !== null) {
_projects.resolve(_storedProjects);
} else {
$http.jsonp('https://www.behance.net/v2/users/zachjanice/projects', {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK',
'page': pageNum
}
})
.then(function (response) {
if (response.data.http_code === 200 && response.data.projects.length > 0) {
// console.log('getting page', _page);
_projects.resolve(response.data.projects);
localStorageService.add('Projects_Page_' + pageNum, response.data.projects);
}
});
}
return _projects.promise;
},
// Get project with id
getProject: function (id) {
var _project = $q.defer();
$http.jsonp('https://www.behance.net/v2/projects/' + id, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_project.resolve(data.project);
});
return _project.promise;
},
// Get project with id
getUser: function (username) {
var _user = $q.defer();
$http.jsonp('https://www.behance.net/v2/users/' + username, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_user.resolve(data.user);
});
return _user.promise;
}
};
});
Anthony Chu supplied no support, so I found the answer myself. The issue was not the Behance Service, but the Projects Controller like I had originally stated.
I changed $scope.loading under the call for the service from false to true. Works every time.

Categories

Resources