AngularJS ng-hide element based on Firebase mode - javascript

Referring to this documentation here, I am trying to hide my element if the mode in the controller function is verifyEmail. No success. Could somebody help to see why it doesn't work?
My HTML is like:
<div class="box-forgot" ng-controller="ResetPass">
<form class="form-forgot" name="resetpassword" ng-hide="mode == 'verifyEmail'">
<fieldset>
<legend>
Reset Password:
</legend>
<div class="form-group">
<span class="input-icon">
<input type="password" class="form-control" id="password" ng-model="user.password" name="password" placeholder="Password" required="">
<i class="fa fa-lock"></i> </span>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary pull-right" ng-click="resetMe()">
Reset
</button>
</div>
</fieldset>
</form>
</div>
And the corresponding controller is:
app.controller("ResetPass", ["$scope","firebase", "$location",
function ($scope,firebase, $location) {
$scope.resetMe = function () {
var newPassword = $scope.user.password;
var actionCode = $location.search().oobCode;
var mode = $location.search().mode;
firebase.auth().confirmPasswordReset(actionCode, newPassword)
.then(function (resp) {
console.log("reset pass, done");
$location.path('/login.signin');
}).catch(function (error) {
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
}]);

Try to bind mode with $scope object instead of var
Instead of
var mode = $location.search().mode;
Do this
$scope.mode = $location.search().mode;

The variable you're trying to reference in your HTML is not visible because it's not in the controller's scope.
You have to change this:
var mode = $location.search().mode;
to this:
var mode = $scope.mode = $location.search().mode;
// or
$scope.mode = $location.search().mode;

Related

ng-view scope communicating with main scope communication

It's maybe a stupid question but it's late and i'm desperate.
I have a angularjs application that uses ngRoute. But everything is done in one controller. Now I have a form in a view and the use of that form is to put it's input field data into a var to send with post.
Don't mind al the console log i'm trying to find the error.
APP.JS
`
$scope.addDevice = function(){
$scope.device = {};
var data = {
'Name' : $scope.device.ChildName,
'Serial' : $scope.device.Serial
};
console.log($scope.device.Serial);
console.log($scope.device.ChildName);
console.log(data);
$http.post('http://141.135.5.117:3500/device/register', data, { headers: headers })
.then(function(response){
console.log(response);
console.log(headers);
});
}`
Settings.html ( Note: this is a view in ng-view)
<form role="form" class='userForm'>
<label for="addDevice">Add Device</label>
<input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="$scope.device.Serial">
<input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="$scope.device.ChildName">
<button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
<p>{{$scope.device.Serial}}</p>
</form>
This is the console output
Console output
All the functions are done in one controller.
First Remove $scope from ng-model="$scope.device.Serial"
and define $scope.device = {}; outside $scope.addDevice = function(){
$scope.device = {};
$scope.addDevice = function(){
-- you code here --
}
Working code example
angular.module('inputExample', [])
.controller('ExampleController', ['$scope','$http', function($scope,$http) {
$scope.val = '1';
$scope.device = {};
$scope.addDevice = function(){
var data = {
'Name' : $scope.device.ChildName,
'Serial' : $scope.device.Serial
};
console.log($scope.device.Serial);
console.log($scope.device.ChildName);
console.log(data);
$http.post('http://141.135.5.117:3500/device/register', data)
.then(function(response){
console.log(response);
console.log(headers);
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="inputExample">
<div ng-controller="ExampleController">
<form role="form" class='userForm'>
<label for="addDevice">Add Device</label>
<input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="device.Serial">
<input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="device.ChildName">
<button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
<p>{{device.Serial}}</p>
</form>
</div>
</div>

AngularJS & Firebase auth ngShow and ngClick delay?

I'm just starting out with AngularJS and I'm running into an odd problem regarding Firebase authentication. I have a very simple body which shows to current user status (logged in, true or false) and a signIn and signOut option.
When I click the Log-in button the first time, nothing happens. When I click it a second time, the logged in status changes and the ng-show and ng-hide divs switch.
Same problem when clicking sign out.
Why does it only happen after the second click?
index.html:
<div class="container" ng-controller="userCtrl">
<h1>User logged in: {{loggedIn}}</h1>
<div ng-hide="loggedIn">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" ng-model="user.email" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" ng-model="user.password" />
</div>
<button type="button" class="btn btn-lg btn-success" ng-click="signIn()">Sign in</button>
</div>
<div ng-show="loggedIn"><button type="button" class="btn btn-lg btn-danger" ng-click="signOut()">Sign out</button></div>
</div>
Controller:
var myApp = angular.module("tijdlozespelApp", ["firebase"]);
myApp.controller("userCtrl", function ($scope, $firebaseObject) {
$scope.loggedIn = false;
$scope.signIn = function() {
var email = $scope.user.email;
var password = $scope.user.password;
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
$scope.loggedIn = true;
}).catch(function(error) {
$scope.loggedIn = false;
});
}
$scope.signOut = function() {
firebase.auth().signOut().then(function() {
$scope.loggedIn = false;
});
}
});
Use $scope.$apply(function() {...}) to update your scope data when you use async handlers. Angular have problems with identifing scope changes for async operations.
$scope.$apply(function() {
$scope.loggedIn = true;
});

Angular/Ionic: Can't access value in html input field

I have the following HTML code:
<div class="list">
<label class="item item-input">
<input id="email" ng-model="email" type="text" placeholder="Email Address">
</label>
<br>
<center>
<button class="button button-positive" ng-click="getData();"> Test </button>
</center>
</div>
And the following Angular code:
$scope.getData = function() {
var emailadd = document.getElementById('email');
var url = "http://172.16.99.138/sendemail.php?emailaddress="+emailadd;
console.log(url);
};
However when I try to run the code, the console says that it can't find the variable. Would appreciate guidance here.
Note: Your code in question is wrong anyway as document.getElementById('email') will get you the dom element, this is not the value() of the element.
Still you should be doing this the "Angular Way" :
You need to define the model in your Controller like so :
$scope.email = {
text: ''
};
Then you can bind in the HTML like so :
<input type="email" name="input" ng-model="email.text" required>
Then you can use the $scope.email in your method :
$scope.getData = function() {
var url = "http://172.16.99.138/sendemail.php?emailaddress="+$scope.email.text;
console.log(url);
};
ng-model Documentation
Use this way of data binding in AngularJs,pass email as parameter in function getData()
<div class="list">
<label class="item item-input">
<input id="email" ng-model="email" type="text" placeholder="Email Address">
</label>
<br>
<center>
<button class="button button-positive" ng-click="getData(email);"> Test </button>
</center>
</div>
And in your controller
$scope.getData = function(email) {
// var emailadd = document.getElementById('email');don't use this
var url = "http://172.16.99.138/sendemail.php?emailaddress="+email;
console.log(url);
};

Angular - Form Validation - Cannot read property 'name' of undefined

so I have a form with an input and some other stuff and I'm trying to do some angular validation to make sure that the entered information is actually there (not blank). To do so, I'm using an if statement.
The error message I get is:
Cannot read property 'name' of undefined
It seems as if it can't read an <input> tag name if it's left blank. The function works when I fill in the , but not the others (which are a and . I'm just trying to use an if statement to see if they've been filled out. Here's the html and angular code below:
reviewModal.view.html (shortened form version)
<div class="modal-content">
<div role="alert" ng-show="vm.formError" class="alert alert-danger">{{ vm.formError }}</div>
<form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
<label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
<div class="col-xs-10 col-sm-10">
<input id="name" name="name" ng-model="vm.formData.name" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit review</button>
</form>
</div>
reviewModal.controller.js
(function() {
angular
.module('loc8rApp')
.controller('reviewModalCtrl', reviewModalCtrl);
reviewModalCtrl.$inject = ['$uibModalInstance', 'locationData'];
function reviewModalCtrl($uibModalInstance, locationData) {
var vm = this;
vm.locationData = locationData;
vm.onSubmit = function() {
vm.formError = "";
if(!vm.formData.name || !vm.formData.rating || !vm.formData.reviewText) {
vm.formError = "All fields required, please try again";
return false;
} else {
console.log(vm.formData);
return false;
}
};
vm.modal = {
cancel : function() {
$uibModalInstance.dismiss('cancel');
}
};
}
})();
locationDetail.controller.js
(function() {
angular
.module('loc8rApp')
.controller('locationDetailCtrl', locationDetailCtrl);
locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'loc8rData'];
function locationDetailCtrl($routeParams, $uibModal, loc8rData) {
var vm = this;
vm.locationid = $routeParams.locationid;
loc8rData.locationById(vm.locationid)
.success(function(data) {
vm.data = { location: data };
vm.pageHeader = {
title: vm.data.location.name
};
})
.error(function(e) {
console.log(e);
});
vm.popupReviewForm = function() {
var modalInstance = $uibModal.open({
templateUrl: '/reviewModal/reviewModal.view.html',
controller: 'reviewModalCtrl as vm',
resolve : {
locationData : function() {
return {
locationid : vm.locationid,
locationName : vm.data.location.name
};
}
}
});
};
}
})();
vm.formData must be defined before you can assigned/read name property in the html. Update code in reviewModalCtrl to init vm.formData:
vm.formData = {};
Use angular validation instated validating things in controller as follows.
<div class="modal-content">
<div role="alert" ng-show="addReview.$submitted && addReview.$invalid" class="alert alert-danger">All fields required, please try again</div>
<form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
<label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
<div class="col-xs-10 col-sm-10">
<input id="name" name="name" ng-model="vm.formData.name" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Submit review</button>
</form>
</div>
I have used required in text box and show the error message on top with
ng-show="addReview.$invalid"
You do not need any code on controller.

Searching through JSON Object with ng-disabled (AngularJS)

One of the features of my web application is the possibility to add new users (username + password) through a form. Thereby, I have one JSON object (l_usernames) defined in a controller (UsersController) with all the usernames already chosen by users to avoid the repetition of usernames (it's a unique key).
Sample of my data (fetched-data.json) - format of object "usernames" (l_usernames):
[{"0":"default","USERNAME":"default"},{"0":"user1","USERNAME":"user1"},{"0":"user2","USERNAME":"user2"},{"0":"user3","USERNAME":"user3"}]
There is a sample of the form to add new users (add-user.html):
<div class="row" ng-controller="UsersController">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Add New User</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputUserUsername" class="col-sm-2 control-label"><i class="icon fa fa-user"></i> USERNAME</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserUsername" placeholder="Username" ng-model="user_username">
</div>
</div>
<div class="form-group">
<label for="inputUserPassword" class="col-sm-2 control-label"><i class="icon fa fa-key"></i> PASSWORD</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputUserPassword" placeholder="Password" ng-model="user_password">
</div>
</div>
</form>
</div>
</div>
<form class="form-inline">
<div class="span7 text-center">
<button type="submit" class="btn btn-success" ng-click="addUser()" ng-disabled="(!user_username || !user_password)">Save</button>
</div>
</form>
</div>
</div>
Sample of my controller (userscontroller.js):
var app = angular.module('myApp');
app.controller('UsersController', ['$scope', 'services', function($scope, services) {
services.getData().then(function(data){
$scope.l_usernames = data.data;
});
}])
.factory('services', ['$http', function($http){
var serviceBase = 'services/'
var object = {};
object.getData = function(){
return $http.get('fetched-data.json');
};
return object;
}]);
I would like to know how it is possible to not allow the insert of new users if the username is already chosen - searching through the JSON object l_usernames - with ng-disabled (by disabling the "Save" button). I also want to print a simple message - "Username already chosen" - if such situation occurs. Thank you.
Add a watch on the user_username scope variable. Whenever it changes search through the JSON object, you can use lodash or underscorejs to search through l_usernames to see if the username already exists. If it exists then set a variable in the scope to false. Bind the ng-disabled of the save button to this variable. Use debounce on the user_username for better performance.
Take a look at this fiddle here
Controller
function UsersController($scope) {
$scope.name = 'Superhero';
$scope.l_username = [{"0":"default","USERNAME":"default"},{"0":"user1","USERNAME":"user1"},{"0":"user2","USERNAME":"user2"},{"0":"user3","USERNAME":"user3"}];
$scope.allowSave = true;
$scope.$watch('user_username', function(value) {
if (_.findWhere($scope.l_username, {"USERNAME": value}) !== undefined)
$scope.allowSave = false;
else
$scope.allowSave = true;
})
}
HTML
<button type="submit" class="btn btn-success" ng-click="addUser()" ng-disabled="!allowSave">Save</button>
Whenever the entered username is found in the array, the allowSave variable is changed which disables the 'save' button.
Note: I have used underscore.js to search through the list. You can use you custom method as well.
I have added the warning message and debounced the model for better performance.
I would make a validation directive.
HTML:
<input username-exists type="text" ng-model="userName" ng-model-options="{updateOn: 'default blur', debounce: { 'default': 700, 'blur': 0 }}" />
<div ng-if="myFormName.$error.usernameExists">Username exists!</div>
<button type="button" ng-disabled="myFormName.$invalid">
The ng-model-options is so that your model doesn't go crazy and update always (it delays the validation).
Javascript:
app.directive('usernameExists', function() {
return {
restrict: 'A', //match attributes only
require: 'ngModel',
scope: {
l_usernames: '='
},
link: function(scope, elem, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
//first, assume the model is valid until proven otherwise
ctrl.$setValidity('usernameExists', true);
if(viewValue.length > 0 && !ctrl.$error.usernameExists) {
for(var i = 0; i < scope.l_usernames.length; ++i) {
if(scope.l_usernames[i].USERNAME === viewValue) {
//username exists, so set valididty to false
//the form is not valid
ctrl.$setValidity('usernameExists', false);
break; //found match
}
}
}
return viewValue;
});
}
};
})

Categories

Resources