How to inject my service into my controller angular js - javascript

I am relatively new to angular JS and I have an issue with angularJS 1.3.0 beta build
I am trying to insert my service (a standalone module) to a controller.
This is my app Code
'use strict';
angular.module('lifecareApp', [
'lifecareApp.validationServices'
, 'lifecareApp.loginController'
, 'lifecareApp.signupController'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/account/login', {
controller: 'loginController'
}).
when('/account/signup', {
controller: 'signupController'
})
$locationProvider.html5Mode(true);
});
This is my service code
'use strict';
angular.module('lifecareApp.validationServices', []).
factory('validationServices', function () {
return {
validateRequiredField: function (value, requiredMessage) {
if (value){
return false; //returns false
}else{
if (requiredMessage){
return requiredMessage;
}else{
return "Required";
}
}
},
validateEmail: function (value, required, requiredMessage, invalidEmailMessage){
//validate if its required first
if (required){
if (value){
//validate the email next
var checkEmailRegex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (checkEmailRegex.test(value)){
return false;
}else{
if (invalidEmailMessage){
return false;
}else{
return "Invalid Email";
}
}
}else{
if (requiredMessage){
return requiredMessage;
}else{
return "Required";
}
}
}
}
};
});
This is my controller code
'use strict';
/* Controllers */
angular.module('lifecareApp.loginController', []).
controller('loginController', ['$scope', 'validationServices' function ($scope, validationServices) {
$scope.emailError = false;
$scope.passwordError = false;
$scope.overallError = false;
$scope.login = function(){
var email = $scope.tbEmail;
var password = $scope.tbPassword;
var passwordValidation = validationServices.validateRequiredField(password);
var emailValidation = validationServices.validateEmail(email, true);
if (emailValidation){
$scope.emailError = true;
$scope.valEmail = emailValidation;
}else{
$scope.valEmail = "";
$scope.emailError = false;
}
if (passwordValidation){
$scope.passwordError = true;
$scope.valPassword = passwordValidation;
}else{
$scope.valPassword = "";
$scope.passwordError = false;
}
if (passwordValidation || emailValidation){
$scope.overallError = true;
$scope.valError = "Login Error!";
return;
}else{
$scope.overallError = true;
$scope.valError = "";
}
};
}]);
And I keep getting this error.
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0-beta.5/$injector/modulerr?p0=lifecareApp&…ngularjs.org%2F1.3.0-beta.5%2F%24injector%2Funpr%3Fp0%3D%2524routeProvider......5)
Please help! =(
I also found out that angular 1.0.7 does not have this error whereas the lastest angular 1.2.16 and 1.3.0 has this error.

In your main module you need to include ngRoute dependency with the new version of angularjs
angular.module('lifecareApp',['ngRoute',....
Also remember to include the route script file
<script src="angular-route.js">

Related

Angular infinite scroll adding broken directive templates every time it gets new data

I am working on a social feed that displays charitable activities. It's supposed to look like the second activity in this image:
But as you can see, every time that angular-infinite-scroll goes to fetch the next batch of activities, it adds a broken template to the top of the feed.
This is the function that's called to get more activities:
feedService.prototype.nextPage = function () {
var fs = this;
if (fs.busy) return;
fs.busy = true;
fs.params.limit = fs.params.limit || _feedLimit;
if (fs.activities.length > 0)
fs.params.idLessThan = fs.activities[fs.activities.length - 1].id;
$http({ url: serviceBase + 'api/stream/getflatfeed', method: 'GET', params: fs.params })
.then(function (response) {
var feed = response.data;
console.dir(feed.results);
console.dir(fs.activities);
if (feed) {
fs.duration = feed.duration;
fs.gStreamMessage = feed.gStreamMessage;
fs.unread = feed.unread;
fs.unseen = feed.unseen;
fs.noMoreActivity = false;
if (response.data.results && response.data.results.length === 0)
fs.noMoreActivity = true;
else {
var acts = _decorateFeedActivities(response.data.results, fs.params);
acts.forEach(function (act) {
var alreadyExists = false;
fs.activities.forEach(function (e, i) {
if (e.id === act.id) {
console.log('alreadyExists!');
alreadyExists = true;
}
});
if (!alreadyExists) {
fs.activities.push(act);
}
});
};
}
fs.busy = false;
}.bind(this));
};
This is the directive used for activities:
feedModule.directive('feedCard', ['$compile', '$http', '$filter', function ($compile, $http, $filter) {
var getTemplate = function (contentType) {
var templateLoader,
baseUrl = 'app/areas/feed/cards/',
templateMap = {
donated: 'general-donation-card-tpl.html',
image: 'image-card-tpl.html',
video: 'video-card-tpl.html',
quote: 'quote-card-tpl.html',
link: 'link.html',
chat: 'chat.html',
audio: 'audio.html',
answer: 'answer.html'
};
var templateUrl = baseUrl + templateMap[contentType];
templateLoader = $http.get(templateUrl);
return templateLoader;
};
return {
restrict: 'E',
scope: {
activity: '=',
user: '='
},
replace: true,
link: linker
};
function linker(scope, element) {
var loader = getTemplate(scope.activity.verb);
var promise = loader.success(function (html) {
element.html(html);
}).then(function (response) {
element.replaceWith($compile(element.html())(scope));
console.log('---------------');
});
}
}]);
And this is the HTML for the infinite-scroll directive and the activities within:
<div class="infinite-scroll" infinite-scroll='feed.nextPage()' infinite-scroll-disabled='feed.busy || feed.noMoreActivity'>
<feed-card class="portlet light bordered feed-card message-card" ng-repeat="activity in feed.activities" activity="activity" user="data.user"></feed-card>
<div class="well" ng-show='feed.busy'>Loading data...</div>
<div class="well" ng-show='feed.noMoreActivity'>There is no more activity on your feed...</div>
</div>
I'm at a loss for what's happening. The additional, broken activities don't appear in any arrays of API returns. I would assume that it's maybe some sort of scoping issue that would cause the directive to fire twice, with one of them being broken?
If anyone has experienced anything like this, I would love to hear your advice. Thank you.
Fixed this by adding "ng-if='activity'" to the feed-card element.

Jhipster generated app, default AngularJS register form

I created an app using JHipster and try to edit the `register.html'. The code where I need help is shows below:
<div class="alert alert-success" ng-show="vm.success" data translate="register.messages.success">
<strong>Registration saved!</strong> Please check your email for confirmation.
</div>
<div class="alert alert-danger" ng-show="vm.error" data-translate="register.messages.error.fail">
<strong>Registration failed!</strong> Please try again later.
</div>
I omitted the rest of the code as they are equal to these two, only with different messages and ng-models . & the register.controller.js :
(function() {
'use strict';
angular
.module('MyApp')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$translate', '$timeout', 'Auth', 'LoginService'];
function RegisterController ($translate, $timeout, Auth, LoginService) {
var vm = this;
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
vm.login = LoginService.open;
vm.register = register;
vm.registerAccount = {};
vm.success = null;
$timeout(function (){angular.element('#login').focus();});
function register () {
if (vm.registerAccount.password !== vm.confirmPassword) {
vm.doNotMatch = 'ERROR';
} else {
vm.registerAccount.langKey = $translate.use();
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
vm.errorEmailExists = null;
Auth.createAccount(vm.registerAccount).then(function () {
vm.success = 'OK';
}).catch(function (response) {
vm.success = null;
if (response.status === 400 && response.data === 'login already in use') {
vm.errorUserExists = 'ERROR';
} else if (response.status === 400 && response.data === 'e-mail address already in use') {
vm.errorEmailExists = 'ERROR';
} else {
vm.error = 'ERROR';
}
});
}
}
}
})();
My question is by default the error handling messages must be hidden, and once the form is valuated, they should be shown based on the condition. But I cannot figure out how to make this work...
Below is the default register.html page:
The generated register.html does not show those messages by default. It looks like you are loading just the HTML file into the browser, but you need to run the app and load the index.html from there to run the Angular code.
Run ./mvnw or ./gradlew and access the frontend at http://localhost:8080
You can also run gulp which will serve your frontend at http://localhost:9000 with live-reloading when you make changes. More info can be found in the Using JHipster in development documentation
The register page looks like the following image when ran correctly:

Can't access to cookies with AngularJS

i can't access to the cookies stored in localhost.
The cookis are already stored (view image)
When i try to display, i get undefined (view image)
Here is my js code for display :
var app = angular.module("Authentification", ['ngCookies']);
app.controller("log", ['$cookieStore', '$scope', '$http', function($cookieStore, $scope, $http) {
$scope.typeEmploye = $cookieStore.get('typeEmploye');
alert($scope.typeEmploye);
}]);
Here is my js code where i store the attribute in cookies after getting the result from my rest API.
var app = angular.module("Authentification", ['ngCookies']);
app.controller("main", ['$cookieStore', '$scope', '$http','$location',
function($cookieStore, $scope, $http, $location) {
$scope.user = [];
$scope.type=[];
$scope.auth = function() {
$http.get("/Employe/authentification?login=" + $scope.log + "&password=" + $scope.pw)
.success(function(data) {
console.log(data);
if (data) {
$scope.user = data;
$cookieStore.put('typeEmploye', $scope.user.type);
$cookieStore.put('Authentified',true);
$scope.type=$cookieStore.get('typeEmploye');
if($scope.type == "gerant"){
window.location.href = "/Gerant/index.html";
}
else if($scope.type == "cuisinier"){
window.location.href = "/Cuisinier/index.html";
}
else if($scope.type == "servant"){
window.location.href = "/Servant/index.html";
}
else{
window.location.href = "/error";
}
}
else{
alert("Login ou mot de passe incorrects");
}
}).error(function(data, status) {
alert("Problème dans le service d'authentification");
});
};
}]);
The information is stored in cookies. But, when i go to an other page ( with a different js file), i can't get the cookies. here is the js code.
var app = angular.module("ger", ['ngCookies']);
app.controller("main", ['$cookies', '$scope', '$http','$location',
function($cookies, $scope, $http, $location) {
var Type = $cookies.typeEmploye;
alert(Type);
}]);

Angularjs - hide div with "if" and "else"

I would only like to show a div when user is logged in and on their profile but disabled when logged off and on another users profile.
I attempted to do this below but was unsuccessful. I would like to know what is the best possible way of going about this?
Service.js
(function () {
'use strict';
angular
.module('app.authentication.services')
.factory('Authentication', Authentication);
Authentication.$inject = ['$cookies', '$http'];
function Authentication($cookies, $http) {
var Authentication = {
getAuthenticatedAccount: getAuthenticatedAccount,
isAuthenticated: isAuthenticated
};
return Authentication;
function getAuthenticatedAccount() {
if(!$cookies.authenticatedAccount) {
return;
}
return JSON.parse($cookies.authenticatedAccount);
}
function isAuthenticated() {
return !!$cookies.authenticatedAccount;
}
})();
Controller.js
(function () {
'use strict';
angular
.module('app.profiles.controllers')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['$location', '$routeParams', 'Posts', 'Profile', 'Snackbar'];
function ProfileController($location, $routeParams, Posts, Profile, Authentication, Snackbar) {
var vm = this;
activate();
function activate() {
var authenticatedAccount = Authentication.getAuthenticatedAccount();
var username = $routeParams.username.substr(1);
// This will show Cog settings button
// when user is logged in and on their profile,
// but hidden when logged off and also when on
// another users profile
if (!authenticatedAccount) {
vm.profileCog = false;
// console.log('User not logged in');
}
else {
if(authenticatedAccount.username !== username) {
vm.profileCog = false;
// console.log('Not logged in user');
}
else {
vm.profileCog = true;
//console.log('logged in user');
}
}
}
})();
profile.html
<div ng-controller="ProfileCogController">
<div ng-show="!profileCog"></div>
</div>
According to your comment that getAuthenticatedAccount is always asynchronous:
This means you'll need to either A) explicitly watch it, or B) evaluate it once it completes. Something like this:
function activate() {
Authentication.getAuthenticatedAccount().then(function(account) {
var username = $routeParams.username.substr(1);
if(!account || account.username !== username) {
vm.profileCog = false;
}
});
// rest of code omitted
You'll need to make sure that Authentication.getAuthenticatedAccount returns a promise for this to work (by default, async calls using AngularJS internal libraries should always return a promise, aka, something that is thenable).
Solved:
controller.js
(function () {
'use strict';
angular
.module('resonanceinn.profiles.controllers')
.controller('ProfileCogController', ProfileCogController);
ProfileCogController.$inject = ['Authentication', '$routeParams', 'Profile'];
function ProfileCogController(Authentication, $routeParams, Profile) {
var vm = this;
vm.profileCog = false;
activate();
function activate() {
var authenticatedAccount = Authentication.getAuthenticatedAccount();
var username = $routeParams.username.substr(1);
if (!authenticatedAccount) {
vm.profileCog = false;
// console.log('User not logged in');
}
else {
if(authenticatedAccount.username !== username) {
vm.profileCog = false;
// console.log('Not logged in user');
} else {
vm.profileCog = true;
// console.log('logged in user');
}
}
}
}
})();
profile.html
<div ng-controller="ProfileCogController">
<div ng-show="vm.profileCog"></div>
</div>
you need to specify the controller and app name in your html file:
1) specify the controller and app name in any parent tag of current div tag if any
2) otherwise, specify the same with in the same div tag
Like:
angular.module('showApp', [])
.controller('mainController', function($scope) {
$scope.isvisible=false;
$scope.showDiv=function()
{
if(!$scope.isvisible)
$scope.isvisible=true
else
$scope.isvisible=false
}
});
<!doctype html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-animate.js"></script>
</head>
<body ng-app="showApp" ng-controller="mainController">
Show me: <input type="checkbox" ng-click="showDiv()" ><br/>
<div ng-show="isvisible">I show up when your checkbox is checked.
</div>
</body>
</html>
Thanks,

AngularJS call Firebase uid from controller

Im trying to verify that a user is logged in. Initially I went with $scope.use, $scope.user.uid, $scope.getCurrenUser() as described on Firebase docs but I think I simply have the dependencies wrong.
Code:
myApp.js
https://gist.github.com/sebbe605/2b9ff7d3b798a58a3886
firebase.js
https://gist.github.com/sebbe605/f9e7b9a75590b3938524
If I understand this correctly there is no way for the program to know that I'm referring to a Firebase user. To clarify I want .controller('templateCtrl',function($scope, $firebase) to have the ability to show a certain button if the user is logged in.
--UPDATE 1--
So, i have updated my files and for what i understand this should work. Previous code are as gits above to enhance the cluther.
myApp.js
angular.module('myApp', [
'ngRoute',
'firebase'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/template',
{
templateUrl:'partials/template.html', controller:'templateCtrl'
});
$routeProvider
.when('/login',
{
templateUrl:'partials/login.html', controller:'signupCtrl'
});
$routeProvider
.when('/signup',
{
templateUrl:'partials/signup.html', controller:'signupCtrl'
});
$routeProvider
.when('/user',
{
templateUrl:'partials/user.html', controller:'userCtrl'
});
$routeProvider
.otherwise('/template');
}])
controllers.js
'use strict';
angular.module('myApp').controller('signupCtrl', function($scope, $http, angularFire, angularFireAuth){
$scope.loginBusy = false;
$scope.userData = $scope.userData || {};
var ref = new Firebase('https://boostme.firebaseio.com/');
angularFireAuth.initialize(ref, {scope: $scope, name: 'user'});
/*//////////////LOGIN - LOGOUT - REGISTER////////////////////*/
$scope.loginEmailText = "Email"
$scope.loginPasswordText = "Password"
$scope.login = function() {
$scope.loginMessage = "";
if ((angular.isDefined($scope.loginEmail) && $scope.loginEmail != "") && (angular.isDefined($scope.loginPassword) && $scope.loginPassword != "")) {
$scope.loginBusy = true;
angularFireAuth.login('password', {
email: $scope.loginEmail,
password: $scope.loginPassword
});
} else {
$scope.loginPassword = ""
$scope.loginPasswordText = "Incorrect email or password"
}
};
$scope.logout = function() {
$scope.loginBusy = true;
$scope.loginMessage = "";
$scope.greeting = "";
$scope.disassociateUserData();
$scope.userData = {};
angularFireAuth.logout();
};
$scope.emailText = "Email"
$scope.passwordText = "Password"
$scope.confirmPasswordText = "Confirm Password"
$scope.register = function() {
$scope.loginMessage = "";
if ((angular.isDefined($scope.email) && $scope.email != "") && (angular.isDefined($scope.password0) && $scope.password0 != "" && $scope.password0 == $scope.password1)) {
$scope.loginBusy = true;
angularFireAuth.createUser($scope.email, $scope.password0, function(err, user) {
if (user) {
console.log('New User Registered');
}
$scope.loginBusy = false;
});
} else {
$scope.password0 =""
$scope.password1 =""
$scope.passwordText = "Password Not Matching"
$scope.confirmPasswordText = "Password Not Matching"
}
};
$scope.$on('angularFireAuth:login', function(evt, user) {
$scope.loginBusy = false;
$scope.user = user;
console.log("User is Logged In");
angularFire(ref.child('users/' + $scope.user.id), $scope, 'userData').then(function(disassociate) {
$scope.userData.name = $scope.userData.name || {};
if (!$scope.userData.name.first) {
$scope.greeting = "Hello!";
} else {
$scope.greeting = "Hello, " + $scope.userData.name.first + "!";
}
$scope.disassociateUserData = function() {
disassociate();
};
});
});
$scope.$on('angularFireAuth:logout', function(evt) {
$scope.loginBusy = false;
$scope.user = {};
console.log('User is Logged Out');
});
$scope.$on('angularFireAuth:error', function(evt, err) {
$scope.greeting = "";
$scope.loginBusy = false;
$scope.loginMessage = "";
console.log('Error: ' + err.code);
switch(err.code) {
case 'EMAIL_TAKEN':
$scope.loginMessage = "That email address is already registered!";
break;
case 'INVALID_PASSWORD':
$scope.loginMessage = "Invalid username + password";
}
});
})
Output:
Error: [$injector:unpr] Unknown provider: angularFireProvider <- angularFire
http://errors.angularjs.org/1.3.0-rc.3/$injector/unpr?p0=angularFireProvider%20%3C-%20angularFire
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:80:12
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:3938:19
at Object.getService [as get] (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4071:39)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:3943:45
at getService (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4071:39)
at invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4103:13)
at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4123:23)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:7771:28
at link (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-route.js:938:26)
at invokeLinkFn (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:7549:9) <div ng-view="" class="ng-scope">
(anonymous function) angular.js:10683
(anonymous function) angular.js:7858
invokeLinkFn angular.js:7551
nodeLinkFn angular.js:7069
compositeLinkFn angular.js:6441
publicLinkFn angular.js:6320
boundTranscludeFn angular.js:6461
controllersBoundTransclude angular.js:7096
update angular-route.js:896
Scope.$broadcast angular.js:13751
(anonymous function) angular-route.js:579
processQueue angular.js:12234
(anonymous function) angular.js:12250
Scope.$eval angular.js:13436
Scope.$digest angular.js:13248
Scope.$apply angular.js:13540
done angular.js:8884
completeRequest angular.js:9099
xhr.onreadystatechange angular.js:9038
I cant figure out what the problem is. However i think there is something wrong with: but i can't tell. If more information is needed i'm happy to post it.
I initially was taking the same if-then-else approach as you do for handling privileged actions. But it turns out this is not the best approach when using Angular. Instead of having this if-then-else approach, try to reframe the problem to a solution that isolates the privileged code.
show a certain button if the user is logged in
So your original question was about showing an HTML element only when the user if logged in, which is easy with something like this in your controller:
$scope.auth = $firebaseSimpleLogin(new Firebase(FBURL));
This line binds the Firebase login status to the current scope, which makes it available to the view. No if-then-else is needed, since there is always a login status. AngularFire ensure that the view gets notified when that status changes, so all we have to do is ensure that we have the HTML markup to handle both presence and absence of authenticated users:
<div ng-controller="TrenchesCtrl" class='auth'>
<div ng-show="auth.user">
<p>You are logged in as <i class='fa fa-{{auth.user.provider}}'></i> {{auth.user.displayName}}</p>
<button ng-click="auth.$logout()">Logout</button>
</div>
<div ng-hide="auth.user">
<p>Welcome, please log in.</p>
<button ng-click="auth.$login('twitter')">Login with <i class='fa fa-twitter'> Twitter</i></button>
<button ng-click="auth.$login('github')">Login with <i class='fa fa-github'> GitHub</i></button>
</div>
</div>
See how it almost reads like an if-then-else? But then one without me writing code that tries to detect if the user is logged in. It is all declaratively handled by AngularJS and AngularFire.
perform actions only when a user is logged in
When you actually need to perform a privileged action, I've found it easiest to isolate the code like this:
function updateCard(id, update) {
var auth = $firebaseSimpleLogin(new Firebase(FBURL));
auth.$getCurrentUser().then(function(user) {
update.owned_by = user.username;
var sync = $firebase(ref.child('cards').child(id));
sync.$update(update);
});
};
Note that these are (simplified) fragments from my Trenches app (demo), which I wrote to learn more about Angular and AngularFire.

Categories

Resources