place localstorage value in a textbox from a controller with angularjs - javascript

I have a localstorage value which i would want to put in it a texfield from a controller
.controller('working_ctrl', ['$scope', '$http', '$location', function ($scope, $http,$location) {
$scope.user= localStorage.getItem("user")
$scope.items = [];
$scope.selected = undefined;
$http({
method: 'GET',
url:'http://localhost/work/templates/spree/work/items.php'
}).then(function (data) {
$scope.items = data.data;
//console.log(JSON.stringify(data));
})
}])
HTML
<div ng-controller="working_ctrl" ng-repeat="s in items| limitTo:1">
<input name="quantity" type="text" id="quantity" ng-model="s.quantity">
<input name="user" type="text" id="user" ng-model="s.user">
</div>

You can bind the $scope.user to that textbox
<input name="user" type="text" id="user" ng-model="user">

your try to put the user in User input field but your input field is present with in ng-repeat so push user data in Array or set the user data in specific array index . like this
.controller('working_ctrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.user = localStorage.getItem("user")
$scope.items = [];
$scope.selected = undefined;
$http({
method: 'GET',
url: 'http://localhost/work/templates/spree/work/items.php'
}).then(function(data) {
$scope.items = data.data;
//console.log(JSON.stringify(data));
$scope.item.forEach(function(value) {
value.user = $scope.user
})
or //
$scope.item[0].user = $scope.user // user specific index
})
}])

Related

AngularJS: how to use session storage when reloading a page

User is filling a form with different types of inputs.
On the same page he also can delete files from a server. After clicking a button a file is deleted, page is reloaded and changes made in other inputs are reset.
I've read a sessionStorage is something for me but currently I even have trouble injecting it. (Error: $injector:unpr Unknown Provider)
I think it delFile function in js controller it should be saving data to session storage, but how and where to retrieve it later?
jsp form:
<form ng-submit="save()">
<div>
Name:
<input type="text" ng-model="myForm.name" />
</div>
<div>
Type:
<select ng-model="myForm.type">
<option ng-selected="{{type.id == myForm.type}}" ng-repeat="type in types" value="{{type.id}}">{{type.description}}</option>
</select>
</div>
<div>
Is new:
<input type="checkbox" ng-model="myForm.isNew">
</div>
<div>
Files to upload:
<input type="file" file-input="filesToUpload" name="file" multiple />
<br>
Server files:
<p ng-repeat="serverFile in serverFiles" >
{{serverFile.name}}
<button type="button" ng-click="delFile(serverFile)">Delete from server</button>
</p>
</div>
<div>
<input type="submit" value="Save it!" />
</div>
</div>
</form>
js controller:
productApp.controller('ProductController', [
'$scope',
'$http',
'$log',
'$modal',
'$filter',
'$routeParams',
'$location',
'$window',
'$sessionStorage',
'productService',
function($scope, $http, $log, $modal, $filter, $routeParams, $location, $window, $sessionStorage, productService) {
$scope.productId= $routeParams.productId;
$scope.types= [];
$scope.myForm = {};
$scope.filesToUpload = [];
productService.getTypes().then(function(response) {
$scope.types = response.data;
});
productService.getServerFiles($scope.productId).then(function(response) {
$scope.serverFiles = response.data;
});
$scope.delFile = function(file) {
productService.deleteFileFromServer(file, $scope.productId);
// here it should be saving data to session storage I believe, but how and where to retrieve it later?
$window.location.reload();
};
$scope.save= function() {
$http({
method: 'POST',
url: '/product/app/save',
headers: {'Content-Type': undefined},
transformRequest: function (data) {
var formData = new FormData();
formData.append('myForm', new Blob([angular.toJson(data.myForm)], {
type: "application/json"
}));
for (var i = 0; i < $scope.filesToUpload.length; i++) {
$log.info("filesToUpload[i]: " + JSON.stringify($scope.filesToUpload[i]));
formData.append('files', $scope.filesToUpload[i]);
}
return formData;
},
data: {
myForm: $scope.myForm,
files: $scope.filesToUpload,
},
}).success(function(data) {
alert("All went well!");
$location.path('/inProgress');
}).error(function(data) {
$scope.$error = 'Error occurred!';
});
};
}
]);
SessionStorage is not an angular dependecy therefor you can not inject it.
If You really want you can create a service that wraps it and then inject service if you want to but it isn't necessary.
SessionStorage is a located on the window object which is global. Which means that you can reach it as such
sessionStorage.setItem("keyname", "YourValueAsString")
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

how to pass back the data from dialog to controller in angularjs?

below is my first controller
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
var newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
In my second controller am trying to send some data to my parent controller as shown below
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
ngDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
ngDialog.close(1, 2);
}
};
}])
below is the ngdialog html. It has 2 textbox which am able to get data to my second controller but not able to send response back to first controller
<form ng-submit="create(form.$valid)" name="form" novalidate="">
<div class="form-flex ng-pristine ng-invalid ng-touched">
<div class="form-tile">
<label>Class name </label>
<input type="text" ng-model="classObj.name" name="form.name" placeholder="Enter the name of your class" required>
<label>Class description</label>
<textarea ng-model="classObj.description" name="form.description" placeholder="Enter a short description" rows="5" required></textarea>
</div>
</div>
<button type="submit" ng-click="submittedForm = true;" ng-disabled="form.$invalid" class="mat-raised-button-blue"> Create </button>
<button class="mat-raised-button" style="float:right; width:155px" ng-click="cancel();"> Cancel </button>
</form>
Am pushing some objects to the array and trying to send but not able to receive it from parent controller.
Where am doing wrong?
After a closer read of the documentation, it looks like you need to call .close() passing the id of the dialog and the value to return from the dialog's controller. In your parent controller the object passed back to your closePromise callback has id and value properties. You'll need to get whatever you're passing back via the value property (i.e. data.value.whateverYouAreReturning). Here is a simple example that returns an object with a single string property.
angular.module('app', ['ngDialog'])
.controller('ctrl', ($scope, ngDialog) => {
$scope.returnedValue = "";
$scope.openModal = function() {
var newClassDialog = ngDialog.open({
template: 'dialogTemplate',
closeByEscape: false,
controller: 'dialogCtrl',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function(data) {
$scope.returnedValue = data.value.result;
});
};
})
.controller('dialogCtrl', ($scope, ngDialog) => {
var id = ngDialog.getOpenDialogs()[0];
$scope.returnValue = "";
$scope.close = () => {
ngDialog.close(id, { result: $scope.returnValue });
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/js/ngDialog.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog-theme-default.min.css">
<div ng-app="app" ng-controller="ctrl">
<button ng-click="openModal()">Open Modal</button>
<p>Returned from dialog: {{ returnedValue }}</p>
<script type="text/ng-template" id="dialogTemplate">
<h1>ngDialog Sample</h1>
<p>
<label>Enter a value to return: </label>
<input type="text" ng-model="returnValue" />
</p>
<p><button ng-click="close()">Close</button></p>
</script>
</div>
This might work (can't test it unless you can share a plunker):
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
$scope.newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
$scope.newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
and in the other controller:
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
$parent.$scope.newClassDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
$parent.$scope.newClassDialog.close(1, 2);
}
};
}])

AngularJS Form and $scope not updating each other

I am trying to make a very minimalistic form in AngularJS (version 1).
I am trying to use ng-model and the $scope to update an object I've named fluff. Once a user clicks submit it should be used in this $http call.
I'm highly confused I thought ng-model would bind this to the object in the scope. But it always returns a blank cause the $scope.fluff is not updating.
Yet if I inject {{ fluff.link }} this will update based on the textbox.
Here is my form in the view:
<form name="fluffForm" ng-submit="submitform()">
<span>Link: <input type="text" name="link" ng-model="form.link"></span>
<span>Description: <input type="text" name="description" ng-model="form.desc"></span>
<button type="submit">submit</button>
</form>
</div>
Here is my controller:
(function(){
'use strict';
angular.module('fluff').controller('FormController', FormController);
FormController.$inject = ['$scope', '$rootScope', '$routeParams', '$window', '$http'];
function FormController( $scope, $rootScope, $routeParams, $window, $http){
var form = this;
$scope.fluff = {}; // form data in json object(?) to be posted to mongo database
$scope.submitform = function(){
$scope.fluff.link = form.link;
$scope.fluff.description = form.desc;
console.log('form-data', $scope.fluff);
$http({
method: 'POST',
url: 'http://fluff.link/share',
data: $scope.fluff,
headers: {'Content-type': 'application/x-www-form-urlenconded'}
}).success(function(data){
console.log('Call to API was successful');
if(data.errors){
console.log('Data Errors');
console.log('error:', $data.errors.name);
//show errors - part of the response in the REST API have to make this portion up myself
$scope.errorName = $data.errors.name;
} else {
console.log('returned share id', data);
var fluff = 'fluff/link/'+ data;
$window.location.href = fluff;
}
});
}
}
})();
Here is my route:
(function(){
'use strict';
angular.module('fluff').config(Config);
Config.$inject = ['$routeProvider'];
function Config($routeProvider){
$routeProvider.when('/', {
templateUrl: 'views/index.client.view.html',
controller: 'FormController',
controllerAs: 'form'
});
}
})();
Added some logs from the developer console in chrome:
in submitform FormController {link: "test", desc: "test"}
fluff.form.controller.js:24 form-data Object {link: undefined}
Got it to work! Will update with my answer when it allows!
So my problem here is that I wasn't using the form controller like I should have.
Here I have the template being loaded with the controller as form.
$routeProvider.when('/', {
templateUrl: 'views/index.client.view.html',
controller: 'FormController',
controllerAs: 'form'
});
In the template I have to use form:
<span>Link: <input type="text" name="link" ng-model="form.link"></span>
<span>Description: <input type="text" name="description" ng-model="form.desc"></span>
then in the controller I create a this object:
var vm = this;
vm is now linked to form.
So now I can do this:
var fluff = {};
fluff.link = form.link;
fluff.description = form.desc;
Now fluff has all the data it needs when my user clicks submit.

How to access $scope variable declared in service callback function in ng-init or ng-checked

I have service.js in which authentication takes place.On success service callback function is executed from controller.js
service.js:
'use strict';
angular.module('Authentication')
.factory('AuthenticationService', ['$http', '$cookieStore', '$rootScope','$timeout', '$location', '$window',
function ($http, $cookieStore, $rootScope, $timeout, $location, $window) {
var service = {};
service.Login = function (username, password, callback) {
$http.post('..json', {
headers: {
username: username,
password: password
}
})
.success(function (data, status, headers, config) {
$timeout(function () {
callback(status);
}, 1000);
});
};
return service;
}])
controller.js:
'use strict';
angular.module('Authentication').controller('LoginController', ['$scope', '$rootScope', '$location', 'AuthenticationService', '$http', '$timeout', '$window',
function ($scope, $rootScope, $location, AuthenticationService, $http, $timeout, $window) {
**$scope.name=true;**
$scope.login = function () {
AuthenticationService.Login($scope.username, $scope.password, function (response) {
if (response === 'Success') {
$http.get('..json').success(data,status,headers,config){
**$scope.value=true;**
})
} else {
alert("Error");
}
});
};
}]);
HTML :
I have 2 checkboxes linked with two $scope variable from controller-$scope.name and $scope.value
<input type="checkbox" ng-checked="name"> abc
<input type="checkbox" ng-checked="value">xyz
Now since both $scope variable is set to true both checkboxes should be initially checked....but the checkbox with $scope.name is checked and $scope.value is unchecked
Any idea about why this happens and how can I make the second check box also initially checked based on the $scope.value
here is a working version almost exactly same as your original code, the only thing i see might be wrong is if (response === 'Success'), because in my example code, the status in .success(data,status,headers,config) is a number not string like "Success", also check this official document here.

Pass data from angular form to another controller

I am new to angularjs. I want to pass data from html form to another route.
Here is the part of index.html
<div ng-app="myApp" ng-controller="HomeController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div ng-view=""></div>
</div>
</div>
</div>
</div>
Here are the routes
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController'
});
$routeProvider.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
});
}]);
When the route is / it hits the views/home.html in which it has a form
<form action="#/about" ng-submit="submitData()">
<input type="text" name="address" ng-model="user.address" />
<input type="submit" />
</form>
I have a user service whose implementation is
myApp.factory("user", function () {
return {};
});
I inject user service in HomeController like
myApp.controller("HomeController", function ($scope, user) {
$scope.user = user;
// and then set values on the object
// $scope.user.address = "1, Mars"; // when uncomment this line it can be accessed on AboutController? Why? Otherwise I cannot access user.address
console.log($scope.user);
});
Don note my comment in above code..
and passes user to AboutController like
myApp.controller("AboutController", function ($scope, user) {
$scope.user = user;
// and then set values on the object
$scope.user.firstname = "John";
$scope.user.secondname = "Smith";
console.log($scope.user);
});
Here is the about.html
<p>
{{ user.address }}
</p>
Problem: {{user.address}} doesn't work on AboutController. I can't see any output... But when i remove the comment from above code.. It only displays hardcoded values in the controller What am I missing?
This is the working demo http://ashoo.com.au/angular/#/
At the moment, all your service does is pass a blank object return {}, to any controller into which it is injected. You need a getter/setter approach, so that in your Home view you can set the data, and in your About view you can retrieve it.
So your service could look something like this:
myApp.factory("user", function () {
var dataObj = {};
return {
setData: function(data) {
dataObj.username = data.username;
},
getData: function() {
return dataObj;
}
};
});
Now you can set the data in your Home controller:
myApp.controller("HomeController", function ($scope, user) {
$scope.submitData = function(data) { //pass in ng-model
user.setData(data); //call 'user' service to set data
}
});
And call it from your About controller:
myApp.controller("AboutController", function ($scope, user) {
$scope.user = user.getData(); //Assign
console.log($scope.user.username);
});
And you html would look like:
<form action="#/about" ng-submit="submitData(user.username)">
<input type="text" name="address" ng-model="user.username" />
<input type="submit" />
</form>

Categories