Submitting form to file angularjs - javascript

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
}
}

Related

Removing from array has side-effects

I am making a form to create orders. The input fields are dynamic and can be added with a button.
Now after every row there is a delete button, which should delete the row.
For this this I made the delRow() function. It works because the row gets deleted, unfortunately the values of the rows underneath it are removed as well, but the input fields stay in place. I can't seem to figure out why.
Template:
<form>
<div class="form">
<table>
<tr ng-repeat="row in rows">
<td>
<input class="product" ng-model="row.product[$index]" placeholder="{{productPlaceholder}}" type="text">
</td>
<td>
<input ng-model="row.amount[$index]" type="number" min="0">
</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>
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, $log) {
$scope.$log = $log;
$scope.message ="test";
$scope.rows = [{}];
$scope.counter = 1;
$scope.productPlaceholder = 'Product';
$scope.addRow = function() {
$scope.rows.push({});
$scope.counter++;
}
$scope.delRow = function(index) {
if ($scope.rows.length < 2) { return; }
$scope.rows.splice(index, 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;
});
});
Instead of:
<input ng-model="row.product[$index]" type="number" min="0">
You should do this:
<input ng-model="row.product" type="number" min="0">
Because you are deleting the rows the index reference is getting thrown off. Instead of using a index reference you can just just place the values directly to a attribute of the object.
I whipped up a working pen here:
http://codepen.io/nilestanner/pen/gmyBRo?editors=1011

AngularJs - how to reload page after adding new data to datatable

I am very new to angularjs and using angularjs bootstrap datatable. Now when I add new record to my datatable it is being updated in mysql database but I need to reload my page so new record can be displayed in table also but I don't know how to do it. Can anyone please help me? Can I init tableRoleCtrl on success of addRoleData() in ui-bootstrp.js?
Here is my code
ui-bootstrap.js
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, content, tableService) {
//add new role
$scope.addRole = function(w) {
tableService.addRoleData(w)
}
})
table.js
.controller('tableRoleCtrl', function($filter, $sce, ngTableParams, tableService) {
//var data = tableService.data;
var self = this;
var promise = tableService.getRoleData();
self.data = [];
promise.then(
function(payload) {
self.data = payload.data;
//alert(JSON.stringify(self.data));
//console.log("test" + self.data)
self.tableEdit = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: self.data.length, // length of data
getData: function($defer, params) {
$defer.resolve(self.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
},
function(errorPayload) {
$log.error('failure loading movie', errorPayload);
});
//to updaate data
self.updateRole = function(w) {
tableService.updateRoleData(w);
}
})
service.js
.factory('tableService', ['$http', function($http){
var _this = this;
return {
// role
getRoleData: function() {
return $http.get("data/getRoles.php");
},
updateRoleData: function(w) {
$http.post("data/updateRole.php", w)
},
addRoleData: function(w) {
$http.post("data/addRole.php", w)
}
}
}])
html
<div data-ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="addrole.html">
<div class="modal-header">
<h4 class="modal-title">Add Role</h4>
</div>
<div class="modal-body m-l-15">
<form role="form">
<div class="row">
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon"><i class="zmdi zmdi-account"></i></span>
<div class="fg-line">
<input type="text" name="role_title" ng-model="add_role.role_title" class="form-control" placeholder="Title">
</div>
</div>
<br/>
<div class="">
<div class="input-group"><span class="input-group-addon"><i class="zmdi zmdi-account-circle"></i></span>
<select chosen multiple>
<option>Use seetings from</option>
<option>HR</option>
<option>Employee</option>
<option>Admin</option>
</select>
</div>
</div>
</div><br/>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="ok(); addRole(add_role)">Submit</button>
<button class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="openStatic('addrole')">Add Roles</button>
</div>
<div class="table-responsive">
<table ng-table="tctrl.tableEdit" class="table table-striped" show-filter="true">
<tr ng-repeat="w in $data" ng-class="{ 'active': w.$edit }" ng-click="ShowHide12()" style="cursor:pointer">
<a href="" ng-click="getSingleRole()">
<td><span ng-if="!w.$edit">{{ w.rl_title }}</span>
<div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.rl_title" /></div>
</td>
</a>
<td>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = true; "><i class="zmdi zmdi-edit"></i></button>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = false"><i class="zmdi zmdi-close"></i></button>
<button type="button" class="btn btn-success" ng-if="w.$edit" ng-click="w.$edit = false; tctrl.updateRole(w)"><i class="zmdi zmdi-check"></i></button>
<button type="button" class="btn btn-default" ng-if="w.$edit" data-ng-click="w.$edit = 0" ><i class="zmdi zmdi-close"></i></button>
</td>
</tr>
</table>
</div>
You don't actually need to reload page when data is updated, AngularJS is MVC framework and each model AngularJS will create a watcher to update view.
Basically, you just need to store your table data to a scope variable $scope.tableData in your controller then use ng-repeat="row in tableData" to iterate your table data. ng-repeat will watch your tableData changes then update your table.
If you changed the ngTable data dynamically, you can refresh it with:
self.tableEdit.reload();

Add image to a list item in AngularJS

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>

AngularJS : View doesn't update when a value in $scope changes

I have an html file with a view that gets it's values from an AngularJS scope.
<form ng-controller="EmployeesController as emp" class="signed-in" ng-submit="logOutUser()">
<div class="row">
<div class="col-md-10 text-left">
<h5>Your Games, {{emp.username}}</h5>
</div>
<div class="col-md-2">
<button class="btn btn-md btn-primary btn-block" type="submit">Log Out</button>
</div>
</div>
<div class="row store">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Games To Buy</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Game Name</th>
<th>Game Status {{what}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="game in emp.games">
<td>{{game}}</td>
<td>
<button ng-click="buyGame(game.gameId)" type="button" class="btn btn-sm btn-primary btn-block" href="#">Buy</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</form>
.
And the js file :
var app = angular.module("MyApp", ['ngRoute']);
app.controller("EmployeesController", function($scope, $http) {
this.games = [{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'}];
this.ownedGames = [];
var that = this;
$scope.sellGame = function(gameId) {
var index = that.ownedGames.indexOf(gameId);
that.ownedGames.splice(index, 1);
$.jStorage.set(that.username, that.ownedGames);
}
$scope.$on('$viewContentLoaded', function() {
if($.jStorage.get('Employee') == null)
$scope.logged = false;
else
$scope.logged = true;
$http.get('employees.json').
success(function(data, status, headers, config) {
that.games = data.games;
that.username = $.jStorage.get('Employee');
if($.jStorage.get(that.username) != null)
that.ownedGames = $.jStorage.get(that.username);
});
});
});
Ok. So basically what the problem is, is that the emp.games variable is empty. First of all it gets commented in the rendered HTML page, and second when i debug the page the variable emp.games is empty. Yet the variable that emp.games is supposed to get its values from, the $scope.games is filled with values as it should be. So the problem is that my emp.games doesn't see that $scope.games was updated in that http request, so IT doesn't update. I googled as much as i could and found out that i should use $scope.apply, but wherever i used it i got the error $digest already in progress... any ideas?
Thanks
Try check diggest
if (!$scope.$$phase) {
$scope.$apply(function () {
that.games = data.games;
})
}
else
that.games = data.games;
Or you can inject $timeout service and use it like this, it will be better.
$timeout (function () {
that.games = data.games;
}, 0)
Your controller definition is not valid, please use like this.
app.controller("EmployeesController", ['$scope','$http','$timeout', function($scope, $http, $timeout){
//....
}]

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>

Categories

Resources