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

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){
//....
}]

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();

How to set data to a service function in AngularJS ng-click

I am trying to persist information inside a service so that I can access the data across controllers. Here is what I tried :
HTML:
<div ng-app="myApp">
<div ng-controller="ControllerOne as one">
<h2>ControllerOne:</h2>
<table>
<tbody>
<tr ng-repeat="emp in EmployeeInfo">
<td>{{emp.name}}</td>
<td>{{emp.hireDate}}</td>
<td><a class="btn-sm btn-primary pull-right" ng-click="storeIds({{emp.idUser}})" >E-Verify</a></td>
</tr>
</tbody>
</table>
Change testService.loginName: <input type='text' ng-model='one.myService.UserId'/> </br></br>
myName: {{one.myService.UserId}}
</div>
<hr>
<div ng-controller="ControllerTwo as two">
<h2>ControllerTwo:</h2>
myName: {{two.myService.UserId}}
</div>
</div>
JS:
app.service('testService', function(){
this.UserId= uId;
});
app.controller('ControllerOne', function($scope, testService){
$scope.storeIds = function (userid) {
// HERE I want to call the testService and set the value.
}
this.myService = testService;
});
app.controller('ControllerTwo', function($scope, testService){
this.myService = testService;
});
have you tried looking into using $rootScope?
app.controller('ControllerOne', function($scope, rootScope, testService){
$scope.storeIds = function (userid) {
// HERE I want to call the testService and set the value.
}
$rootScope.myService = userid;
});
app.controller('ControllerTwo', function($scope, ,rootScope, testService){
//rootScope.myService will now equal whatever the userid was in the other controller.
//I skipped using the service
});

AngularJS - object not passed to modal dialog

I have a problem with an AngularJS app I'm making. It shows a list of contacts, and for each contact there is a button whereupon clicking the button a modal pops up with a form. This form should show the existing contact information, and if you want to change something you type the new information and press submit.
The problem, however, is that the existing information is not shown in the form, hence editing it doesn't work. I imagine that the issue is that the modal does not inherit the scope from the parent page, but I don't know what to do in order to fix that. I have tried playing around with the attributes on the input fields (for example prepending ng-model by $parent. and defining an ng-init value), but to no avail, so I hope some of the experts here will be able to point me on the right track.
Thank you in advance.
Now let me show you my code, so you can see the context I'm talking about. Here is the html that displays the list of contacts:
<div class="panel panel-default" ng-controller="contactsController">
<div class="panel-body">
<div id="gridContainer" ng-class="{'': state == 'list', 'none': state != 'list'}">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th scope="col"><spring:message code="contacts.name"/></th>
<th scope="col"><spring:message code="contacts.email"/></th>
<th scope="col"><spring:message code="contacts.phone"/></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in page.source">
<td class="tdContactsCentered">{{contact.name}}</td>
<td class="tdContactsCentered">{{contact.email}}</td>
<td class="tdContactsCentered">{{contact.phoneNumber}}</td>
<td class="width15">
<div class="text-center">
<input type="hidden" value="{{contact.id}}"/>
<a ng-href="#updateContactsModal"
ng-click="selectedContact(contact);"
role="button"
title="<spring:message code="update"/> <spring:message code="contact"/>"
class="btn btn-sm btn-warning" data-toggle="modal">
<i class="icon-pencil"></i>
</a>
<a ng-href="#deleteContactsModal"
ng-click="selectedContact(contact);"
role="button"
title="<spring:message code="delete"/> <spring:message code="contact"/>"
class="btn btn-sm btn-danger" data-toggle="modal">
<em class="fa fa-trash"></em>
</a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
And the html that defines the modal and the form:
<div id="updateContactsModal"
class="modal fade centering"
role="dialog"
aria-labelledby="updateContactsModalLabel"
aria-hidden="true" style="display: none;">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 id="updateContactsModalLabel" class="modal-title">
<spring:message code="update"/> <spring:message code="contact"/>
</h3>
</div>
<div class="modal-body" data-ng-controller="contactsController">
<form name="updateContactForm" novalidate>
<input type="hidden"
required
data-ng-model="contact.id"
name="id"
value="{{contact.id}}"/>
<div>
<div class="form-group">
<label>* <spring:message code="contacts.name"/>:</label>
<input type="text"
autofocus
required
class="form-control"
data-ng-model="contact.name"
name="name"
placeholder="<spring:message code='contact'/> <spring:message code='contacts.name'/> "/>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.name.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
<div class="form-group">
<label>* <spring:message code="contacts.email"/>:</label>
<div class="input-append">
<input type="text"
required
class="form-control"
ng-model="contact.email"
name="email"
placeholder="<spring:message code='sample.email'/> "/>
</div>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.email.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
<div class="form-group">
<label>* <spring:message code="contacts.phone"/>:</label>
<div class="input-append">
<input type="text"
required
class="form-control"
ng-model="contact.phoneNumber"
name="phoneNumber"
placeholder="<spring:message code='sample.phone'/> "/>
</div>
<div>
<span class="alert alert-error"
ng-show="displayValidationError && updateContactForm.phoneNumber.$error.required">
<spring:message code="required"/>
</span>
</div>
</div>
</div>
</form>
<div class="modal-footer">
<input type="submit"
class="btn btn-primary"
ng-click="updateContact(updateContactForm);"
value='<spring:message code="update"/>'/>
<button class="btn btn-default"
data-dismiss="modal"
ng-click="exit('#updateContactsModal');"
aria-hidden="true">
<spring:message code="cancel"/></button>
</div>
</div>
<span class="alert alert-error dialogErrorMessage"
ng-show="errorOnSubmit">
<spring:message code="request.error"/>
</span>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
And finally the relevant parts of the controller:
App.controller('contactsController', ["$scope", "$http", function($scope,$http) {
$scope.pageToGet = 0;
$scope.state = 'busy';
$scope.lastAction = '';
$scope.url = "/uaiContacts/protected/contacts/";
$scope.errorOnSubmit = true;
$scope.errorIllegalAccess = false;
$scope.displayMessageToUser = false;
$scope.displayValidationError = false;
$scope.displaySearchMessage = false;
$scope.displaySearchButton = false;
$scope.displayCreateContactButton = false;
$scope.contact = {};
$scope.searchFor = "";
$scope.getContactList = function () {
var url = $scope.url;
$scope.lastAction = 'list';
$scope.startDialogAjaxRequest();
var config = {params: {page: $scope.pageToGet}};
$http.get(url, config)
.success(function (data) {
$scope.finishAjaxCallOnSuccess(data, null, false);
})
.error(function () {
$scope.state = 'error';
$scope.displayCreateContactButton = false;
});
};
$scope.populateTable = function (data) {
if (data.pagesCount > 0) {
$scope.state = 'list';
$scope.page = {source: data.contacts, currentPage: $scope.pageToGet, pagesCount: data.pagesCount, totalContacts : data.totalContacts};
if($scope.page.pagesCount <= $scope.page.currentPage){
$scope.pageToGet = $scope.page.pagesCount - 1;
$scope.page.currentPage = $scope.page.pagesCount - 1;
}
$scope.displayCreateContactButton = true;
$scope.displaySearchButton = true;
} else {
$scope.state = 'noresult';
$scope.displayCreateContactButton = true;
if(!$scope.searchFor){
$scope.displaySearchButton = false;
}
}
if (data.actionMessage || data.searchMessage) {
$scope.displayMessageToUser = $scope.lastAction != 'search';
$scope.page.actionMessage = data.actionMessage;
$scope.page.searchMessage = data.searchMessage;
} else {
$scope.displayMessageToUser = false;
}
};
$scope.exit = function (modalId) {
$(modalId).modal('hide');
$scope.contact = {};
$scope.errorOnSubmit = false;
$scope.errorIllegalAccess = false;
$scope.displayValidationError = false;
};
$scope.finishAjaxCallOnSuccess = function (data, modalId, isPagination) {
$scope.populateTable(data);
$("#loadingModal").modal('hide');
if(!isPagination){
if(modalId){
$scope.exit(modalId);
}
}
$scope.lastAction = '';
};
$scope.startDialogAjaxRequest = function () {
$scope.displayValidationError = false;
$("#loadingModal").modal('show');
$scope.previousState = $scope.state;
$scope.state = 'busy';
};
$scope.handleErrorInDialogs = function (status) {
$("#loadingModal").modal('hide');
$scope.state = $scope.previousState;
// illegal access
if(status == 403){
$scope.errorIllegalAccess = true;
return;
}
$scope.errorOnSubmit = true;
$scope.lastAction = '';
};
$scope.addSearchParametersIfNeeded = function(config, isPagination) {
if(!config.params){
config.params = {};
}
config.params.page = $scope.pageToGet;
if($scope.searchFor){
config.params.searchFor = $scope.searchFor;
}
};
$scope.selectedContact = function (contact) {
$scope.contact = angular.copy(contact);
debugger;
};
$scope.updateContact = function (updateContactForm) {
if (!updateContactForm.$valid) {
debugger;
$scope.displayValidationError = true;
return;
}
$scope.lastAction = 'update';
var url = $scope.url + $scope.contact.id;
$scope.startDialogAjaxRequest();
var config = {};
$scope.addSearchParametersIfNeeded(config, false);
$http.put(url, $scope.contact, config)
.success(function (data) {
$scope.finishAjaxCallOnSuccess(data, "#updateContactsModal", false);
})
.error(function(data, status, headers, config) {
$scope.handleErrorInDialogs(status);
});
};
$scope.getContactList();
}]);
The modal doesn't share the same scope as the contacts table because each time Angular finds another ng-controller directive, it creates a new scope.
You're declaring ng-scope in both the contacts table and the modal, which causes angular to create different scopes.
See this answer for more details:
https://stackoverflow.com/a/14462341/4938335
There are a few ways to solve this...
1) Put the modal HTML inside the parent element where you're already declaring ng-controller the first time - that way it will be part of the same scope
2) Use UI Bootstrap's modal directive to generate the modal with its own controller and pass in $scope.contact from your contactsController. See example here https://angular-ui.github.io/bootstrap/#/modal
3) Create a service that stores $scope.contact and inject that into a separate controller that you create for the modal. Here's someone else's fiddle that shows this:
http://jsfiddle.net/whnSs/

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