Add image to a list item in AngularJS - javascript

I have a simple shopping list and need to be able to upload an image to individual list items. Using MongoDB and AngularJS.
The image should be bound to the $scope.list.items therefore adding an image to a list item (eg. a picture of bread). How can I upload an image and bind it as part of that object? Basically the list of items would also contain images once this is complete.
HTML for displaying items:
<ul class="list-group">
<li style="color:{{list.color}}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()">
{{item.name}} - {{item.priority}}
<i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>&nbsp
<i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
<small class="form-text text-muted">Note: {{item.note}}</small>
<div ng-show = "showEdit">
<h4>Edit {{item.name}}</h4>
<form ng-submit="editItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
<button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
</form>
</div>
<br>
</li>
</ul>
Here is the HTML for adding an item:
<button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
<div ng-show="showAddItem" class="add-item">
<h4>Add Item</h4>
<form ng-submit="addItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="newItem.name" placeholder="Item" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="newItem.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="newItem.note" placeholder="Note" maxlength="255" value= " ">
<button class="btn btn-default btn-add" type="submit">Add</button>&nbsp<span class="close-box" ng-click="showAddItem = !showAddItem"><u>close</u></span>
</form>
<!-- <button class="btn btn-default btn-lg btn-custom" href="">Add Item</button> -->
</div><br><br>
<a ng-href="#/home"><button class="btn btn-default btn-lg btn-home">Save & Return</button></a>
</div>
And the controller for adding an item:
(function () {
'use strict';
var app = angular.module('myApp');
app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = [];
var id = $routeParams.id;
$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};

I modified your code to add an image to the list, and then altered the list item display to check for properties:
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
<img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />
And I made a simple function to add an image item that has an imageSrc property, used in the image that only appears if that property is set.
$scope.list.items.push({
imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
priority: '',
note: 'Evan',
//don't include this property - which will make the ng-show for the checkbox false
//isChecked: true,
created: new Date(),
id: -1
});
. This is one way to do it but you could do it differently.
Sample
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.constant('API_BASE','/api');
app.config(['$routeProvider', function($routeProvider) {}]);
app.controller('ShoppingListController', ['$scope','$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = {items: []};
$scope.showAddItem = true;
var id = $routeParams.id;
//commenting this out because we don't have access to your server
/*$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});*/
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
};
$scope.addImage = function(){
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
priority: '',
note: 'Evan',
//don't include this property - which will make the ng-show for the checkbox false
//isChecked: true,
created: new Date(),
id: -1
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<div ng-app="myApp" ng-controller="ShoppingListController">
<script src="script.js"></script>
<button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
<div style="font-style: italic">//code for adding item
<ul class="list-group">
<li style="color:{{ list.color }}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
<img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />
{{item.name}} - {{ item.priority }}
<i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>
<i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
<small class="form-text text-muted">Note: {{ item.note }}</small>
<div ng-show = "showEdit">
<h4>Edit {{ item.name }}</h4>
<form ng-submit="editItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
<button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
</form>
</div>
<br>
</li>
</ul>
<button ng-click="addImage()" >Add image</button></div>

Related

Submitting form to file angularjs

I am trying to make a dynamic form for creating orders. With the add button it appends an input form so you can add more products per order when necessary.
Now I want to parse the form data to a JSON file, but how would I do that?
I've tried it with using field.product and field.amount as ng-models but it isn't working because when I type in a product in one row, the same text is in all the other rows as well.
<form>
<div class="form">
<table>
<tr ng-repeat="content in rows">
<td>
<input class="product" ng-model="field.product" placeholder="{{content.product}}" type="text">
</td>
<td>
<input ng-model="field.amount" type="number" min="0" value="1" type="text">
</td>
<td>
<button class="btn btn-primary btn-functionality btn-danger btn-del" ng-click="delRow($index)">x</input>
</td>
</tr>
</table>
<button class="btn btn-primary btn-success btn-add" ng-click="addRow()">+</button>
</div>
<div class="main-buttons">
<button class="btn btn-primary btn-lg btn-create" ng-click="createOrder()">Create</button>
<button class="btn btn-primary btn-lg" ng-click="cancelOrder()">Cancel</button>
</div>
</form>
<div style="text-align: center; font-size: 20px; border: 2px solid red; margin: 20px" ng-repeat="order in orders.data track by $index">
<div ng-repeat="product in order">
{{product.product}}
{{product.amount}}
</div>
</div>
Controller:
'use strict';
angular.module('myApp.orderNew', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/order/new', {
templateUrl: 'order-new/order-new.template.html',
controller: 'OrderNewCtrl'
});
}])
.controller('OrderNewCtrl', function($scope, $location, $http) {
$scope.field = {
amount: '1'
};
$scope.rows = [{
product: 'Product',
amount: 'Amount'
}];
$scope.counter = 1;
$scope.addRow = function() {
$scope.rows.push({
product: 'Product',
amount: 'Amount'
});
$scope.counter++;
}
$scope.delRow = function(row) {
if ($scope.rows.length < 2) { return; }
$scope.rows.splice(row, 1);
}
$scope.cancelOrder = function() {
$location.path('/orders');
}
$scope.createOrder = function() {
var data = $scope.fields;
alert(data);
//$post('/path_to_server', obj);
}
$http.get('orders.json').then(function(data) {
$scope.orders = data;
});
});
I'm not completely clear what you're asking, but it sounds like you want your models to each be unique for each repeated item in ng-repeat. If that's the case I would set the ng-model's to ng-model="field.product[$index]" and ng-model="field.amount[$index]"
make your question more clearly , but if you want submitform with ng-click , here is solution
$scope.field={}
$scope.createOrder = function(){
$http({
method:'post',
url:'yoururl',
data:$.param($scope.field),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess)
function onSuccess(response){
///handle when success
}
}

pulling user input from modal form (angular)

I currently have a modal form setup and working nicely how i want it but now i need to grab the information inputed into textboxes and selections by the user and im sort of lost as to where i need to start. below is the code for my modal form in entirity. I'm not necessarily looking for a direct answer but to be pointed in the right direction of more information though examples would be greatly appreciated.
<div ng-app='plunker' ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>Create a new post</h3>
</div>
<form name="modalForm">
<div class="modal-body">
<div class="form-group" ng-class="{ 'has-error': modalForm.modalInput.$invalid }" >
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" placeholder="Post Title" required/><br>
<textarea name="modalInput" class="form-control" rows="10" maxlength="1000" form="modalForm" ng-model="data.myNumber2" placeholder="Post Body" required></textarea><br>
<label for="sel1">Select category:</label>
<select name="modalInput" class="form-control" ng-model="data.myNumber3" id="sel1" required>
<option value="" selected disabled>Please select</option>
<option value='lifestyle'>lifestyle</option>
<option value='travel'>travel</option>
<option value='video'>video</option>
</select><br>
<input name="modalInput" type="url" class="form-control" size="10" ng-model="data.myNumber4" placeholder="http://www.postUrlHere.com"/>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-disabled="modalForm.$invalid" ng-class="{ 'disabled': modalForm.$invalid }" ng-click="ok()">Submit</button>
<button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</div>
</form>
</script>
<h1>GWAT Websites and Designs</h1>
<button class="btn" ng-click="open()">Submit new post</button>
</div>
<script>
var myMod = angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $uibModal, $log) {
$scope.items = ['title', 'body', 'category', 'url'];
$scope.open = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
items: function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
edit:
var ModalInstanceCtrl = function($scope, $uibModalInstance, data) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function() {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
};
myMod.controller('ModalDemoCtrl', ModalDemoCtrl);
myMod.controller('ModalInstanceCtrl', ModalInstanceCtrl);
</script>
If you are looking to send the $scope.data from the current page to a modalInstance, you will have to add a property to the resolve object.
$scope.open = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
data: function() {
return $scope.data;
}
}
});
From the ModalInstanceCtrl, add "data" as a dependency, and you will be able to retrieve the relevant data.

Sending Form Data to the Sever using AngularJS/NodeJS

I want to send form Data from my HTML/AngluarJS page by POST to the server (NodeJS), When submit I'm getting 400 (Bad request)
HTML Page that uses ng-submit:
<div class="container start" ng-controller="adminController">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-body"><h1>Administration</h1>
<!-- form -->
<form class="form-signin" ng-submit="submit()" ng-controller="adminController">
<h2 class="form-signin-heading">Add new Bird</h2>
<select name= "tagType" id= "inputTag" class="form-control" placeholder="Tag Type" ng-modal="bird.tagType">
<option ng-repeat="tag in tags" value="{{option.id}}">{{tag.tagName}}</option>
</select><br/>
<button class="btn btn-primary" ng-click="addTag()">Add Tag</button>
<br/><br/>
<select name = "specie" id= "inputSpecie" class="form-control" placeholder="Specie Category" ng-modal="bird.specie">
<option ng-repeat="specie in species" value="{{option.id}}">{{specie.latinName}}</option>
</select>
<br/>
<button class="btn btn-primary" ng-click="addSpecie()">Add Specie</button>
<br/><br/>
<input type="text" id="inputSex" class="form-control" placeholder="Sex" ng-modal="bird.sex"/>
<br/><br/>
<input type="text" id="inputRFID" class="form-control" placeholder="RFID Value" ng-modal="bird.rfid"/>
<br/><br/>
<textarea id="inputComment" class="form-control" placeholder="Comment" ng-modal="bird.comment"></textarea>
<br/><br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar" />
<br/><br/>
<input class="btn btn-lg btn-primary btn-block" type="submit" id="submit" value="Submit" />
</form>
</div>
</div>
My Controller Script
angular.module('test').controller('adminController', function($scope, $http)
{
$http.get('/api/adminPanel').then(function (response) {
// create a blank object to handle form data.
$scope.bird = {};
$scope.species = response.data.species;
$scope.tags = response.data.tags;
$scope.submit = function()
{
console.log(" Get fields values and Insert in the DB !");
// posting Data to server
$http.post('/api/adminPanel/create', {'bird': $scope.bird}).then(function (response) {
// sucess post
});
// failure post
}
});
});
Database script (adminPanel.js)
router.post('/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// var birdSpecie = req.body.specie;
// console.log(" the Bird specie is " + birdSpecie);
console.log('the post request: ' + JSON.stringify(req.body));
database.addAnimal(specie,sex,comment).then(function()
{
res.sendStatus(200);}
,next);
});
your controller should be something like
angular.module('test').controller('adminController', function($scope, $http){
$scope.bird = {};
$scope.submit = function() {
$http.post('/api/adminPanel/create', $scope.bird).then(function (response) {
console.log(response);// as you need
});
};
});
and your server side should be:
router.post('/api/adminPanel/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// your rest of code
return res.status(200).send("success") // return 200 and success message
});

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

Getting data from modal AngularJS

I am trying to get data FROM modal to invoking controller, and all the examples I have found only describe way to get data to modal.
What is the proper way to do it?
This is a form I am using in modal:
<form class="form-horizontal">
<div class="modal-body">
<div class="control-group">
<label class="control-label">Name:</label>
<div class="controls">
<input type="text" ng-model="transaction.name" placeholder="Transaction name" />
</div>
</div>
<div class="control-group">
<label class="control-label">Category</label>
<div class="controls">
<input type="text" ng-model="transaction.category" placeholder="Category" />
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="text" ng-model="transaction.amount" placeholder="Amount" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<input type="text" datepicker-popup="dd-MMMM-yyyy" ng-model="transaction.date" is-open="opened" min="minDate" max="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" />
<button class="btn" ng-click="open()"><i class="icon-calendar"></i></button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn pull-left" data-dismiss="modal">
<i class="icon-remove"></i> Cancel
</button>
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction()">
<i class="icon-ok icon-white"></i> Save Changes
</button>
</div>
These are controllers:
moneyApp.controller("TransactionController", function($scope, $http, $modal, $log) {
console.log("modal: ", $modal);
$scope.transaction = {}
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'partials/modal.html',
controller: 'ModalInstanceController',
resolve: {
transaction: function() {
return $scope.transaction;
}
}
});
modalInstance.result.then(function (receivedTransaction) {
$scope.selected = receivedTransaction;
console.log("Transaction received: ", transaction);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$http({method: 'GET', url: 'transactions/15/all/'}).success(function(data) {
$scope.transactions = data; // response data
});
})
and
moneyApp.controller("ModalInstanceController", function($scope, $modalInstance, $http, transaction) {
$scope.createTransaction = function() {
console.log("Transakcja: ", $scope.transaction);
$scope.transaction.budgetId = 15;
$scope.selected = {
item: $scope.transaction
}
$http({method: 'POST', url: 'transactions/add/', data : $scope.transaction, headers:{'Accept': 'application/json', 'Content-Type': 'application/json; ; charset=UTF-8'}}).success(function(data) {
console.log("Transaction succesfully added to a DB...");
});
}
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I am trying to invoke method createTransaction, $scope.transaction is undefined. How to get data from this form?
I think you need to assign transaction to $scope.transaction in your ModalInstanceController because you are passing in the transaction object but not putting it into $scope.
$scope.transaction = transaction
In your Modal form you need to pass the ng-model object(ie transaction) to the function (createTransaction()) which gets called on form submit.
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction(transaction)">
<i class="icon-ok icon-white"></i> Save Changes
</button>
And in your controller add the object as parameter to the java-script function.
$scope.createTransaction = function(transaction) {
console.log("transaction details: "+ transaction.category+" "+transaction.amount);
};
Let me know if you are facing any issues, i can share the working code of mine.

Categories

Resources