Angularjs checkbox initialization issue using json object - angularjs

So i have a checkbox page barely working, the issue is when i first start this page, the checkbox is not checked, even though i try to initialize it from backend node server. No error in browser debugger though.
in the server mye,
app.get('/2getMyDiagValue', function(req, res)
{
console.log("get my diag");
var formDataArray = { "formDataObjects": [
{"flagName":"myStuff1", "flagVal":0},
{"flagName":"myStuff2", "flagVal":1}
]};
res.contentType('application/json');
res.send(formDataArray);
});
app.post('/2setMyDiagValue', function(req, res)
{
......
}
in the client mye,
app.controller('myDiagController', function($scope, $http, $routeParams, QueryMyService) {
$scope.message = 'SID Diagnostics';
// using http.get() to get existing my setting from server mye
QueryMyService.getInfoFromUrl7('/2getMyDiagValue').then(function(result) {
$scope.formData = result.formDataObjects;
}, function(error) {
alert("Error");
} );
$scope.submitForm = function() {
console.log("posting form data ...");
$http.post("/2setMyDiagValue",
JSON.stringify($scope.formData)).success(function(){} );
};
});
app.factory('QueryMyService', function($http, $q, $location) {
var factory = {};
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
//////////////////////////////////////////////////////////
factory.getInfoFromUrl7 = function(myUrl) {
var deferred = $q.defer();
$http.get(myUrl).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
return factory;
}
checkbox webpage itself
<form ng-submit="submitForm()" ng-controller="myDiagController">
<div class="control-group" style="color:black">
<label>My Checkbox</label>
<div class="checkbox">
<label class="checbox-inline" >
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff1"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff1 == 1">
<h4>Message 1</h4>
<input class="big-checkbox" type="checkbox" ng-model="formData.myStuff2"
ng-true-value="1" ng-false-value="0" ng-checked="formData.myStuff2 == 1">
<h4>Message 2</h4>
</label>
</div>
<br>
<input class="btn-primary" type="submit">
</form>
i did try to modify ng-checked like this and the checkbox did show checked.
ng-checked="true"

well, just used "res.json" in the node.js side and made it work, guess i just don't have time to learn, while this fxxking company gave me a tough schedule

Related

Why isn't the form sending the text value from my form?

I'm following a tutorial to create a simple todo app using the MEAN stack. Everything was working fine until I moved the controllers and services into separate files. Now I can create a new todo but it doesn't get the text value. I can see in my mongoDB database that a new entry has been created but it doesn't have a text value. I've been looking all over my code but I can't find anything nor do I get any error or warnings in the developer tools of the browser.
Here is the code for the form:
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- Bind this value to formData.text in Angular -->
<input type="text" class="form-control input-lg text-center" placeholder="Add a todo" ng-model="formData.text">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
Here is my service:
//todos.js service
//the service is meant to interact with our api
angular.module('todoService', [])
//simple service
//each function returns a promise object
.factory('Todos', function($http){
return {
get : function() {
return $http.get('/api/todos');
},
create : function(todoData){
return $http.post('/api/todos', todoData);
},
delete : function(id){
return $http.delete('/api/todos/' + id);
}
}
});
Here is my main controller which uses the service:
//main.js
var myApp = angular.module('todoController', []);
myApp.controller('mainController', ['$scope', '$http', 'Todos', function($scope, $http, Todos){
$scope.formData = {};
//GET
//get all the todos by using the service we created
Todos.get()
.success(function(data){
$scope.todos = data;
});
//CREATE
$scope.createTodo = function(){
Todos.create($scope.formData)
.success(function(data){
$scope.formData = {};
$scope.todos = data;
});
}
//DELETE
$scope.deleteTodo = function(id){
Todos.delete(id)
.success(function(data){
$scope.todos = data;
});
};
}]);
Lastly, here is the route for creating a todo:
var Todo = require('./models/todos');
//expose our routes to our app with module exports
module.exports = function(app){
//api
//get all todos
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if(err)
res.send(err);
res.json(todos);
});
});
//create to do
app.post('/api/todos', function(req, res){
Todo.create({
text: req.body.text,
done: false
}, function(err, todo){
if(err)
res.send(err);
//get and return all todos after creating the new one
Todo.find(function(err, todos){
if(err)
res.send(err);
res.json(todos);
});
});
});
To recap, for some reason the formData.text value doesn't get stored somewhere and I don't know why.
I can't say for sure with angular but normal HTML forms inputs need a name attribute to submit

Login in angularjs

I have an idea of how to use post method for login, however, our new requirement is my API team has provided get method. How is this used in angular? Please help me. I am stuck on this problem as I am new to angular. Below is the API for get method:
http://183.82.48/HospitalManagementSystem/Service1.svc/LoginVerification/{EMAILID}/{PASSWORD}
You can try to construct the URI yourself.
<form ng-app="login" ng-controller="loginCtrl">
<span>Email</span><input ng-model="emailId" type="text" required><br>
<span>Password</span><input ng-model="password" type="password" required><br>
<button ng-click="login()">Login</button>
</form>
<script>
var app = angular.module('login', []);
app.controller('loginCtrl', function($scope, $http) {
$scope.login = function() {
$http.get('http://183.82.0.48/HospitalManagementSystem/Service1.svc/LoginVerification/' + $scope.emailId + '/' + $scope.password).then(
function (response) {
console.log(response.data);
// ...
},
function (error) {
console.log(error);
// ...
}
)
}
});
</script>

Display dropdown on tick of checkbox

// I have written java code to fetch data from mongo-db. What i need to do is on tick of checkbox button i have to display those data in drop-down menu using angular-js and bootstrap. Nothing is happening after doing these code.
.html page
<div ng-controller="release">
<div class="col-md-2 col-centered col-fixed">
<label for="cloneRelease" translate="release.form.cloneRelease">CloneRelease</label>
</div>
<div>
<input type="checkbox" ng-model="ticked">
<div class="dropdown-menu" ng-repeat="release in releaseName" ng-show="ticked">{{release.name}}</div>
</div>
</div>
controller.js
releaseApp.controller('release', function($scope, $location, $http, ReleaseNameService){
$scope.releaseName = [];
init();
function init(){
ReleaseNameService.getReleaseName().then(function(data){
$scope.releaseName = data;});
console.log('inside controller: '+$scope.releaseName);
}
});
service.js
releaseApp.factory('ReleaseNameService', function($http){
var releaseName = [];
var factory = {};
factory.getReleaseName = function(){
return $http.get('release/fetchAllReleaseDetails').then(function(response){
releaseName = response.data;
console.log('inside service method'+ releaseName);
return releaseName;
});
};factory;
});
It is simple, u need to bind checkbox with ng-model:
<input type="checkbox" ng-model="ticked">
If its ticked $scope.ticked return true, else return false. If true show data, if false hide it (with ng-show)
Here is an example in jsFiddle without css ofc.
http://jsfiddle.net/RLQhh/2282/
UPDATE:
recreateing case with service.
service.js
app.factory('dataService', function ($http) {
var dataObject= {
async: function () {
var promise = $http.get('data/').then(function (response) {
return response;
});
return promise;
}
};
return dataObject;
})
controller.js
$scope.dataTest = [];
$scope.ticketed = false;
var getData = function(){
dataService.async().then(function (d) {
$scope.dataTest = d.data;
});
}
getData();
html
<input type="checkbox" ng-model="ticketed">
<div ng-show="ticketed" ng-repeat="dat in dataTest">
{{dat.name}}
</div>
...this is tested case so it should work with yours
You can make a REST call to fetch the data from your java function and store it in scope.Then you can use ng-repeat to display data in dropdown.
Here is a very good article on how to do it.
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/29/how-to-work-with-the-bootstrap-dropdown-in-angularjs.aspx

Angularjs model not updated when switching between users at login

I need the following functionality: When a user goes to the login form, the browser should auto fill the username and password.
My implementation works (on FF and Chrome) but, there is this bug (not consistent) where the model data does not get updated correctly when switching between users. This means that I log in with user ONE, then log out, and enter the credentials for user TWO, but after I click the login button, I'm still logged in with user ONE.
The login form looks like this:
<form class="form-horizontal" ng-submit="login(credentials)">
<fieldset>
<div class="form-group" ng-class="{'has-error' : validationErrors.email}">
<div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input type="email" name="email" autocomplete="on" ng-model="credentials.email" class="form-control input-lg input-round text-center" placeholder="Email" >
<span class="help-block" ng-if="validationErrors.email">{{ validationErrors.email.0 }}</span>
</div>
<div class="form-group" ng-class="{'has-error' : validationErrors.password}">
<div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light">
<span class="glyphicon glyphicon-lock"></span>
</div>
<input type="password" name="password" autocomplete="on" ng-model="credentials.password" class="form-control input-lg input-round text-center" placeholder="Password" >
<span class="help-block" ng-if="validationErrors.password">{{ validationErrors.password.0 }}</span>
</div>
<div class="form-group">
<input type="submit" value="Sign in" class="btn btn-primary btn-lg btn-round btn-block text-center">
</div>
</fieldset>
</form>
The login controller contains something like:
// Login Controller
app.controller( 'LoginCtrl', ['$rootScope','$scope', '$state', 'AppUser', 'Auth',
function($rootScope, $scope, $state, AppUser, Auth){
console.log("LoginCtrl");
$scope.credentials = {
"email" : "",
"password": ""
};
$scope.redirectAfterLogin = function() {
// set user data
AppUser.setUserData($scope.user);
...
}
// Login attempt handler
$scope.login = function(data) {
data = {'user':data};
Auth.login(data,
function(response) {
$scope.user = response.data;
...
},function(response){
$scope.validationErrors = {
"email" : [],
"password": []
};
...
}
);
};
}]);
Logout:
// logout
$scope.logout = function() {
// remove attempted URL, if any
AppUser.removeAttemptUrl();
data = {'user':
{
'email': $scope.user.email
}
};
Auth.logout(data,
function(){
AppUser.unSetUserData($scope.user); // se method below
$state.go(ApplicationState.LOGIN);
},
function(){
console.log("Logout failed");
});
}
angular.module('app.service').factory('AppUser', [
'$window', '$rootScope', 'LocalStorage', 'appConfig', '$injector', '$location',
function($window, $rootScope, localStorage, appConfig, $injector, $location){
// Redirect to the original requested page after login
var redirectToUrlAfterLogin = { url: '' };
var userKey = "AppUser";
var userData = {};
angular.element($window).on('storage', function(event) {
if (event.key === userKey) {
$rootScope.$apply();
}
});
return {
/**
* Redirect to the original requested page after login
* - we need to be able to save the intended URL, request it, remove it and redirect to it
*/
saveAttemptUrl: function() {
if ($location.path().toLowerCase() != ApplicationState.LOGIN) {
redirectToUrlAfterLogin.url = $location.path();
}
else {
redirectToUrlAfterLogin.url = '/';
}
},
getAttemptedUrl: function() {
return redirectToUrlAfterLogin.url;
},
removeAttemptUrl: function() {
// re-initialize URL
redirectToUrlAfterLogin = { url: '' };
},
redirectToAttemptedUrl: function() {
$location.path(redirectToUrlAfterLogin.url);
},
/**
* Returns the current user's state
* #returns {boolean}
*/
isAuthenticated: function() {
userData = JSON.parse(localStorage.get(userKey) || '{}').userData;
if (!this._isSessionExpired()) {
if (userData !== undefined){
return !!(userData.id !== null && userData.email);
}
else{
return false;
}
}
else{
if (userData !== undefined){
var data = {
'user':{
'email': userData.email
}
}
// we use $injector to avoid Circular Dependency which is thrown by injecting the $api service
$injector.invoke(['$api', function($api){
$api.auth.logout(data).success(function(result){
userData = {};
localStorage.remove(userKey);
});
}]);
return false;
}
}
},
getUserData: function() {
return userData;
},
setUserData: function(data) {
userData = data;
localStorage.set(userKey, JSON.stringify({
userData: data,
stamp: Date.now()
}));
},
unSetUserData: function() {
userData = {};
localStorage.remove(userKey);
},
_isSessionExpired: function() {
var session = JSON.parse(localStorage.get(userKey) || '{}');
return (Date.now() - (session.stamp || 0)) > appConfig.sessionTimeout;
},
userData : userData
};
}] );
Any ideas on why this is happening?
After you logout check the localStorage with the browser inspector.
Probably you will find some variable that you didn't clear.
So just clear the storage and it should be fine.
To clear the storage use:
localStorage.clear();
One additional problem it could be you didn't clean the $rootScope if you didn't refresh all the data are still in there.
Is this the problem? userKey doesn't seem to be defined in the code you've showed.
// add userKey param
unSetUserData: function(userKey) {
userData = {};
localStorage.remove(userKey);
},

Using $rootscope to change ng-show between controllers

What I want to do is pretty simple. I have two forms. One form is visible in the beginning and once that form is submitted it dissappears and the second form appears. I am trying to use a flag variable set at $rootscope.showFlag but it doesn't seem to work.
Here is my HTML part:
<div ng-app="myapp" >
<div class="container" ng-controller="addItemController" ng-show="showFlag">
<form class="form-signin">
<h2 class="form-signin-heading">Add an item</h2>
<input type="text" name="itemName" ng-model="myForm.itemName" id="inputItemName" class="form-control" placeholder="Name of the item" autofocus required>
<button class="btn btn-lg btn-primary btn-block" ng-click="myForm.submitTheForm()">Add item</button>
</form>
</div> <!-- /container -->
<div class="container" ng-controller="MyCtrl" ng-show="!showFlag">
<input type="text" ng-model="username"></br></br>
<button class="btn btn-lg btn-primary btn-block" ngf-select ng-model="files">Select file</button>
</div>
</div>
And this is my Angular app:
var app = angular.module("myapp", ['ngFileUpload'])
.run(function($rootScope) {
$rootScope.showFlag = true;
});
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
Data.Show = 10;
$scope.myForm.submitTheForm = function(item, event)
{
console.log("--> Submitting form");
var dataObject = {
itemName : $scope.myForm.itemName,
};
var responsePromise = $http.post("/angularjs-post", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
//alert("Submitting form OK!");
$rootScope.showFlag = false;
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
$scope.myForm.uploadPhoto = function(item, event)
{
console.log('Uploading photo');
}
});
app.controller('MyCtrl', ['$scope', 'Upload', function ($rootScope, $scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.log = '';
$scope.upload = function (files) {
if (files && files.length) {
var file = files[0];
Upload.upload({
url: '/upload',
fields: {
'username': $scope.username
},
file: file
}).progress(function (evt) {
// during progress
}).success(function (data, status, headers, config) {
// after finishing
});
}
};
}]);
You set showFlag to true in two places.
In the root scope.
.run(function($rootScope) {
$rootScope.showFlag = true;
});
And in the local scope.
app.controller("addItemController", function($rootScope, $scope, $http) {
$scope.myForm = {};
$scope.showFlag = true;
As the ng-show for the first form looks in the local scope first it won't be affected even when you set the rootScope flag to false.
One possible reason could be that you have misspelled the controller name
it should be addSellItemController.
<div class="container" ng-controller="addSellItemController" ng-show="showFlag">
Another small mistake is you have not added $rootScope as a dependency in your MyCtrl directive.
app.controller('MyCtrl', ['$rootScope','$scope', 'Upload', function ($rootScope, $scope, Upload) {
...
});

Resources