AngularJS ng-show and ng-hide doesn't work - javascript

having a problem with angularjs logic here
I want to show the login link only when there is no user loggedin, and only show the logout link to logged in user, but it doesnt work properly
my HTML
<section ng-controller="a" ng-show="auth = false">
Sign in
</section>
<section ng-controller="b" ng-show="auth = true">
Sign out
</section>
The sign in is working well
this is my Controller
login Controller
function ($scope, Service){
$scope.auth = true;
$scope.signin = function($event, userID, passwd){
Service.signin(userID,passwd).then(
function (response){
$scope.auth = true;
});
}]).
logout Controller
function ($scope, Service){
$scope.auth = false;
$scope.signout = function($event){
Service.signout().then(
function (response){
$scope.auth = false;
});
}]).
those 2 log out and log in links are basically in my main page. I dont want to create a lot of pages, therefore I want to hide each other. When the user click the log in link, it will run the angularjs router, in this case /login, there is another templateURL for the form and it will be appended directly to the main page. Once the user has typed in the userID and password, the user need to click submit button, this is the code
<form role="form" name="form1">
<label for"userID">UserID</label><input type="text" id="userID" ng-model="userID">
<label for"passwd">Password</label><input type="text" id="passwd" ng-model="passwd">
<button data-ng-click="signin($event,userID,passwd); reload()">Login</button>
the reload() function will directly refresh the page. I am using the $window.location.reload()

Your equals comparison is incorrect.
This is assigning a value of false to auth:
ng-show="auth = false"
What you want is this (double and triple equals do comparisons)
ng-show="auth === false"
You can also do this:
<section ng-controller="a" ng-show="!auth">
Sign in
</section>
<section ng-controller="b" ng-show="auth">
Sign out
</section>

Actually You need Two works for this task
First Work:-
You need to assign auth varibale in $rootScope not $scope. because this object used in two controller.
Like
function ($scope, dataService, $rootScope){
$scope.auth = true;
$scope.signin = function($event, userID, passwd){
Service.signin(userID,passwd).then(
function (response){
$rootScope.auth = true;
});
}]).
Second Work:
You need to change ng-show="auth = false" to ng-show="auth === false". You have used single equal. it should be double or triple equal
OR
if you assigned the object in $rootScope, then you don't need to check the condition for is true or false in the element. because you already define auth is false or true in your controller. So you can just call ng-show="auth only.

Just try the followingng-show="auth"
Please let me know if it is still not working..

Related

How to fix ng-if not reacting?

I'm trying to display a link <a href> when a condition is met, but the link never appears.
I have already tried to change the position (in/out of <div controller>) and the tag of the item containing the ng-if (span, div, ul...). This kind of code works on another HTML I have, so my Angular version seems okay.
Here is the form where I call the controller:
<div ng-controller="userRole">
<form ng-submit="setProfile()">
<select ng-model="userRole"
ng-options="role for role in roles">Role</select>
<input type="text"
ng-model="userName"
placeholder="Nom"></input>
<input type="submit"
value="Valider"></input>
</form>
</div>
The condition right after:
<span ng-if="user.isSetup">
Accès aux cours
</span>
And the actual controller:
var app = angular.module('srsApp', []);
app.controller('userRole', function($scope) {
$scope.roles = ['Professeur', 'Élève'];
$scope.user = {role:'', name:'', isSetup: false};
$scope.setProfile = function() {
if ($scope.userName !== '' && $scope.userRole !== '') {
$scope.user.role = $scope.userRole;
$scope.user.role = $scope.userName;
$scope.user.isSetup = true;
$scope.userRole = '';
$scope.userName = '';
}
};
});
</script>
I expected the link to appear once I submit the form with a role and a name, but the link stays hidden. No error from my Firefox terminal, and I know it enters the function because the placeholders are re-initialized.
As mentionned by #AnuragSrivastava, the <span> should be in the <div ng-controller="userRole">. As I said I tried it, but previous circumstances (syntax errors NOT highlighted by terminal) prevented this to work.

AngularJS: Problems with Binding in eventhandlers inside of ng-repeat

I'm trying to display buttons for choosing a username with ng-repeat. The display is OK. But every button in the loop has a ng-click directive with a binding. This is also displayed correct in Google Chromes DOM-Explorer. But when one of the buttons is clicked the eventhandling function login() has {{user.userId}} as input instead the value of the parameter.
Hers my code:
<div class="cell large-3" ng-repeat="user in userData()" ng-class="{'large-offset-1': ($index % 3) != 0}">
<button ng-click="login('{{user.ID}}')" class="button expanded red bigButton"> {{user.userName}} </button>
</div>
Cntrl:
(function () {
'use strict';
angular.module('app').controller('loginCntrl', ['$scope', '$controller', '$location','dataService', 'mainService', initLoginCntrl]);
function initLoginCntrl($scope, $controller,$location, dataService, mainService) {
angular.extend(this, $controller('baseCntrl', {
$scope: $scope
}));
$scope.userData = dataService.getUserData;
$scope.login = function(userID) { <-- input of userid is {{userData.ID}} instead of the eal userID from Binding
mainService.login(userID);
}
}
})();
Thanks for your help in advance!
ng-click="login('{{userData.ID}}')" -> ng-click="login(userData.ID)"
You are passing a string into that function.

Using 'Ng-If' "breaks" program on a $('#x').change or an angularfire $add

I've noticed two instances in my code where using ng-if causes my program to start working. On one, I do an ng-if="isOwnProfile", for an image-upload toolbar.
Using the ng-if causes the event listener to stop working. Code example:
$scope.myOwnProfile = false;
if (userLoggedIn === userUID) {
console.log('my images');
$scope.myOwnProfile = true;
} else {
console.log('not my images');
}
$("#image-upload").change(function(e) {
$scope.myOwnProfile = true;
var file = e.target.files[0];
var imageRef = firebase.storage().ref...
and in HTML:
<section ng-if="myOwnProfile">
<input id="image-upload" type="file" accept="image/*"> <br /><br />
</section>
In this case the event listener will stop working and not respond.
Another case is where you add a message to the page (and firebase).
Code:
$scope.addMessage = function(){
var date = new Date();
$scope.messages.$add({
timestamp: (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear(),
from: $scope.visitorRealName.name,
content: $scope.message
});
$scope.message = '';
};
HTML:
<section ng-if="AreWeFriends === true || myOwnProfile === true">
<form ng-submit="addMessage()">
<input ng-model="message">
<button type="submit">Add Message</button>
</form>
</section>
In the second case I get an error from Firebase "Key content was undefined. Cannot pass undefined in JSON. Use null instead".
I can't determine why using ng-if causes this to happen? What I do is set the user's profile to true whether they are a) a friend or b) it's the person's own profile (which is why I change $scope).
That's because the ngIf directive creates it's own child scope.
The ngIf directive creates it's own scope, so the ngModel directive containing message is set on the scope created by the ngIf directive, not your controller.
When you access the value in your controller it's not there, so it's undefined. You are essentially passing undefined to your content key inside your object you're adding to your messages so Firebase complains.
To fix it i'd recommend using the controller as syntax so that you can reference the controller, or use the ngShow directive, which doesn't create it's own child scope.
Here are a few examples of what happens:
(function() {
'use strict';
angular.module('app', []);
})();
(function() {
'use strict';
angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$scope'];
function MainController($scope) {
var vm = this;
$scope.test1 = test1;
$scope.test2 = test2;
$scope.test3 = test3;
$scope.test4 = test4;
function test1() {
// this is undefined because there is no property `message`
// on the $scope of this controller
alert($scope.message);
}
function test2() {
// this contains the value binded to the message property
// of this controller because we used the controller as syntax
alert(vm.message);
}
function test3(message) {
// because we are passing in the message value we can
// access it without caring where it came from
alert(message);
}
function test4() {
// the property `message` exists on this $scope because we
// used the ngShow directive instead of the ngIf
alert($scope.message4);
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as MainCtrl">
<h4>Without controller as syntax</h4>
<p>Does not work because message is not set on the controller's $scope, it's set on the scope created by the ngIf directive</p>
<form ng-if="true">
<input ng-model="message">
<button ng-click="test1()">Submit</button>
</form>
<hr>
<h4>With controller as syntax</h4>
<p>Works because message is set on the controller so we can access it using `this` in our MainController</p>
<form ng-if="true">
<input ng-model="MainCtrl.message">
<button ng-click="test2()">Submit</button>
</form>
<hr>
<h4>Without controller as syntax but passing the message value into our function</h4>
<p>Works because although message is set on the scope created by the ngIf directive, we are passing it to test3 in our MainController.</p>
<form ng-if="true">
<input ng-model="message">
<button ng-click="test3(message)">Submit</button>
</form>
<hr>
<h4>With ngShow directive instead of ngIf</h4>
<p>Works because message is set on $scope from our contoller</p>
<form ng-show="true">
<input ng-model="message4">
<button ng-click="test4()">Submit</button>
</form>
</div>

Ng-model with Cookie

I'm trying to take the first example from the angular.js homepage and adding in cookie support.
This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/
It is:
<div ng-app="myApp">
<div ng-controller="MyController as mc">
<label>Name:</label>
<input type="text" ng-model="mc.user" placeholder="Enter a name here">
<hr>
<h1>Hello {{mc.user}}!</h1>
</div>
</div>
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', [function($cookies) {
this.getCookieValue = function () {
$cookies.put('user', this.user);
return $cookies.get('user');
}
this.user = this.getCookieValue();
}]);
But it's not working, ive been trying to learn angular.
Thanks
I'd suggest you create a service as such in the app module:
app.service('shareDataService', ['$cookieStore', function ($cookieStore) {
var _setAppData = function (key, data) { //userId, userName) {
$cookieStore.put(key, data);
};
var _getAppData = function (key) {
var appData = $cookieStore.get(key);
return appData;
};
return {
setAppData: _setAppData,
getAppData: _getAppData
};
}]);
Inject the shareDataService in the controller to set and get cookie value
as:
//set
var userData = { 'userId': $scope.userId, 'userName': $scope.userName };
shareDataService.setAppData('userData', userData);
//get
var sharedUserData = shareDataService.getAppData('userData');
$scope.userId = sharedUserData.userId;
$scope.userName = sharedUserData.userName;
Working Fiddle: https://jsfiddle.net/y7dxa6n8/10/
I have used the cookie service between two controllers. Fill out the text box to see how it gets utilized.
ok, examined your code once again, and here is your answer
https://jsfiddle.net/wz3kgak3/
problem - wrong syntax: notice definition of controller, not using [] as second parameter
If you are using [] in controller, you must use it this way:
myApp.controller('MyController', ['$cookies', function($cookies) {
....
}]);
this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies
problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;
problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:
$watch('user', function(newValue) {
$cookies.user = newValues;
});
or do it via some event (click, submit or i dont know where)
EDIT: full working example with $scope
https://jsfiddle.net/mwcxv820/

Submit form on page load in Angular

I would like to submit a search form on page load if search terms were specified in the route. The problem is that searchForm isn't defined yet when search() runs. I've seen others get this to work by putting ng-controller right on the form element, but I have multiple forms on this page, so the controller has to be a parent of the forms.
How can I ensure the form is defined when I call search()?
myModule.controller('MyController', ['$scope', '$routeParams',
function($scope, $routeParams){
$scope.model = {searchTerms: ""};
$scope.search = function(){
if($scope.searchForm.$valid){
...
}
};
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
}]);
View:
<div ng-controller="MyController">
<form name="searchForm" ng-submit="search()">
...
</form>
<form name="detailForm" ng-submit="save()">
...
</form>
</div>
This seems to work:
$scope.$on('$routeChangeSuccess', function () {
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
});
Have you tried just using $watch on searchForm?
if($routeParams.terms != "") {
var unregister = $scope.$watch(function() {
return $scope.searchForm;
}, function() {
// might want to wrap this an if-statement so you can wait until the proper change.
unregister(); //stop watching
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
});
}

Categories

Resources