use column in angularjs uigrid - angularjs

I am using angularjs uigrid with $scope http to get data from controller.
now here i used columns like this:
<div ng-app = "myapp" ng-controller="HelloController">
<div id="grid1" ui-grid="{ data: myData }" class="grid"></div>
</div>
<script type="text/javascript">
var StudentApp = angular.module('myapp', ['ui.grid']);
StudentApp.controller('HelloController', function ($scope, StudentService) {
$scope.columnDefs = [
{ field: 'FirstName', title: 'fname' },
{ field: 'Last Name' },
{ field: 'Salary' },
{ field: 'DOB' }
],
getStudents();
function getStudents() {
StudentService.getStudents()
.success(function (studs) {
$scope.myData = studs;
console.log($scope.students);
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
console.log($scope.status);
});
}
});
StudentApp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Home/GetEmployee');
};
return StudentService;
} ]);
</script>
in this i have used $scope.columndefs but it is not working.
And how to format date value here?
When i run this apps value is showing in below like after some 30 lines value is showing.

Try this
<div ng-app = "myapp" ng-controller="HelloController">
<div id="grid1" ui-grid="gridoptions" class="grid"></div>
</div>
<script type="text/javascript">
var StudentApp = angular.module('myapp', ['ui.grid']);
StudentApp.controller('HelloController', function ($scope, StudentService) {
$scope.columnDefs = [
{ field: 'FirstName', title: 'fname' },
{ field: 'Last Name' },
{ field: 'Salary' },
{ field: 'DOB' }
],
$scope.gridoptions = {
data:'myData',
columnDefs: $scope.columnDefs,
}
getStudents();
function getStudents() {
StudentService.getStudents()
.success(function (studs) {
$scope.myData = studs;
console.log($scope.students);
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
console.log($scope.status);
});
}
});
StudentApp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Home/GetEmployee');
};
return StudentService;
} ]);
</script>
I hope this would work.

Related

Webix + angularjs datatable from controller

I have the problem, because datatable is empty, data doesn't binding.
html:
<div id="usersFormDiv" ng-controller="adminController">
<div webix-ui="usersGrid"></div>
</div>
controller
$scope.usersGrid ={
view:"datatable",
id:"usersGridWebix",
autoConfig:true,
select:"row",
data : [
{ id:1,"lp":1, "name":1994,"surname":678790,"email":"xxx#xp.pl","organ":"ogran","location":"Lokalizacja 1, Lokalizacja 2"}
],
columns:[
{ header:"Lp", id:"lp", width:50},
{ header:"ImiÄ™", id:"name", width:50},
{ header:"Nazwisko", id:"surname", width:100},
{ header:"Email", id:"email", width:150},
{ header:"Organ", id:"organ", width:100},
{ header:"Lokalizacja", id:"location", width:150}
]
// url: "./app/model/users.json"
};
with webix-ui attribute in div use webix-data="data"
also put
$scope.data = { id:1,"lp":1, "name":1994,"surname":678790,"email":"xxx#xp.pl","organ":"ogran","location":"Lokalizacja 1, Lokalizacja 2"}
I have the same problem, i fixed using this way, for more details refer:-
http://docs.webix.com/desktop__angular.html
You can define the data table structure either on html or within controller as well.
if (window.angular)
(function() {
function id_helper($element) {
//we need uniq id as reference
var id = $element.attr("id");
if (!id) {
id = webix.uid();
$element.attr("id", id);
}
return id;
}
function locate_view_id($element) {
if (typeof $element.attr("webix-ui") != "undefined")
return $element.attr("id");
return locate_view_id($element.parent());
}
//creates webix ui components
angular.module("webix", [])
.directive('webixUi', ["$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attrs, $controller) {
var dataname = $attrs["webixUi"];
var callback = $attrs["webixReady"];
var watch = $attrs["webixWatch"];
var wxRoot = null;
var id = id_helper($element);
$element.ready(function() {
if (wxRoot) return;
if (callback)
callback = $parse(callback);
//destruct components
$element.bind('$destroy', function() {
if (wxRoot && !wxRoot.$destructed && wxRoot.destructor)
wxRoot.destructor();
});
//ensure that ui is destroyed on scope destruction
$scope.$on('$destroy', function() {
if (wxRoot && !wxRoot.$destructed && wxRoot.destructor)
wxRoot.destructor();
});
//webix-ui attribute has some value - will try to use it as configuration
if (dataname) {
//configuration
var watcher = function(data) {
if (wxRoot) wxRoot.destructor();
if ($scope[dataname]) {
var config = webix.copy($scope[dataname]);
config.$scope = $scope;
$element[0].innerHTML = "";
wxRoot = webix.ui(config, $element[0]);
if (callback)
callback($scope, {
root: wxRoot
});
}
};
if (watch !== "false")
$scope.$watch(dataname, watcher);
watcher();
} else {
//if webix-ui is empty - init inner content as webix markup
if (!$attrs["view"])
$element.attr("view", "rows");
var ui = webix.markup;
var tmp_a = ui.attribute;
ui.attribute = "";
//FIXME - memory leaking, need to detect the moment of dom element removing and destroy UI
if (typeof $attrs["webixRefresh"] != "undefined")
wxRoot = ui.init($element[0], $element[0], $scope);
else
wxRoot = ui.init($element[0], null, $scope);
ui.attribute = tmp_a;
if (callback)
callback($scope, {
root: wxRoot
});
}
//size of ui
$scope.$watch(function() {
return $element[0].offsetWidth + "." + $element[0].offsetHeight;
}, function() {
if (wxRoot) wxRoot.adjust();
});
});
}
};
}])
.directive('webixShow', ["$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attrs, $controller) {
var attr = $parse($attrs["webixShow"]);
var id = id_helper($element);
if (!attr($scope))
$element.attr("hidden", "true");
$scope.$watch($attrs["webixShow"], function() {
var view = webix.$$(id);
if (view) {
if (attr($scope)) {
webix.$$(id).show();
$element[0].removeAttribute("hidden");
} else
webix.$$(id).hide();
}
});
}
};
}])
.directive('webixEvent', ["$parse", function($parse) {
var wrap_helper = function($scope, view, eventobj) {
var ev = eventobj.split("=");
var action = $parse(ev[1]);
var name = ev[0].trim();
view.attachEvent(name, function() {
return action($scope, {
id: arguments[0],
details: arguments
});
});
};
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attrs, $controller) {
var events = $attrs["webixEvent"].split(";");
var id = id_helper($element);
setTimeout(function() {
var first = $element[0].firstChild;
if (first && first.nodeType == 1)
id = first.getAttribute("view_id") || id;
var view = webix.$$(id);
for (var i = 0; i < events.length; i++) {
wrap_helper($scope, view, events[i]);
}
});
}
};
}])
.directive('webixElements', ["$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attrs, $controller) {
var data = $attrs["webixElements"];
var id = id_helper($element);
if ($scope.$watchCollection)
$scope.$watchCollection(data, function(collection) {
setTimeout(function() {
var view = webix.$$(id);
if (view) {
view.define("elements", collection);
view.refresh();
}
}, 1);
});
}
};
}])
.directive('webixData', ["$parse", function($parse) {
return {
restrict: 'A',
scope: false,
link: function($scope, $element, $attrs, $controller) {
var data = $attrs["webixData"];
var id = id_helper($element);
if ($scope.$watchCollection)
$scope.$watchCollection(data, function(collection) {
if (collection) {
setTimeout(function() {
loadData($element, id, collection, 0);
}, 1);
}
});
}
};
}]);
function loadData($element, id, collection, num) {
if (num > 10) return;
var first = $element[0].firstChild;
if (first && first.nodeType == 1)
id = first.getAttribute("view_id") || id;
var view = webix.$$(id);
if (view) {
if (view.options_setter) {
view.define("options", collection);
view.refresh();
} else {
if (view.clearAll)
view.clearAll();
view.parse(collection);
}
} else {
webix.delay(loadData, this, [$element, id, collection], 100, num + 1);
}
}
})();
{
"student": [ {
"firstName": "Ajinkya", "lastName": "Chanshetty", "contact": 9960282703, "email": "aajinkya#hotmail.com"
}
,
{
"firstName": "Sandip", "lastName": "Pal", "contact": 9960282703, "email": "sandip#hotmail.com"
}
,
{
"firstName": "Neha", "lastName": "Sathawane", "contact": 99608882703, "email": "neha#hotmail.com"
}
,
{
"firstName": "Gopal", "lastName": "Thakur", "contact": 9960000703, "email": "gopal#hotmail.com"
}
]
}
<!doctype html>
<html lang="en" ng-app="webixApp">
<head>
<meta charset="utf-8">
<title>Webix - Angular : Layouts</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.webix.com/edge/webix.css">
<script type="text/javascript" src="https://cdn.webix.com/edge/webix.js"></script>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
var app = angular.module('webixApp', ["webix"]);
app.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json').then(function(response) {
$scope.content = response.data.student
})
})
app.controller('extCtrl', function($scope, $http) {
$scope.myTable = {
view: "datatable",
columns: [{
id: "name",
header: "Name",
css: "rank",
width: 150
},
{
id: "username",
header: "UserName",
width: 150,
sort: "server"
},
{
id: "email",
header: "Email ID",
width: 200,
sort: "server"
},
{
id: "website",
header: "Website",
width: 150
}
],
autoheight: true,
autowidth: true,
url: "https://jsonplaceholder.typicode.com/users"
}
})
</script>
</head>
<body>
<div webix-ui type="space">
<div height="35">Welcome to Angular Webix App </div>
<div view="cols" type="wide" margin="10">
<div width="200">
<input type="text" placeholder="Type something here" ng-model="app"> Hello {{app}}!
</div>
<div view="resizer"></div>
<div view="tabview" ng-controller="jsonCtrl">
<div header="JSON Data Fetch Example">
<div ng-controller="jsonCtrl">
<div webix-ui view="datatable" webix-data="content" autoheight="true" select="row" fillspace="true">
<div autowidth="true" view="column" id="firstName" sort="int" css="rating" scrollY="true">First Name</div>
<div view="column" id="lastName" sort="int">Last Name</div>
<div view="column" id="contact" sort="int">Contact</div>
<div view="column" id="email" sort="string" width="200">E mail</div>
</div>
</div>
</div>
</div>
<div view="resizer"></div>
<div view="tabview" ng-controller="extCtrl">
<div header="External Source Data Table">
<div webix-ui="myTable"></div>
</div>
</div>
</div>
</div>
</body>
</html>

Displaying data in ng-grid by clicking on an <a> element in the sidebar

I have a view in an angularjs application with a sidebar, where I can choose my insurers. By clicking on an insurer, I want my ng-grid show me some insurer's data. Now I can select the insurer, and see the <div class="well well-sm"> changes.
Here is my angular controller:
app.controller('ReportsInsurerPaymentsCtrl', ['$scope', '$http', '$filter', 'toaster', '$state', '$modal', function ($scope, $http, $filter, toaster, $state, $modal) {
$scope.insurer_payments = [];
$scope.insurer_payments = [];
$scope.insurer_payment = {};
$scope.gridOptions = {
data: "insurer_payment",
rowTemplate: '<div ng-style="{\'cursor\': row.cursor, \'z-index\': col.zIndex() }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell {{col.cellClass}} " ng-cell></div>',
columnDefs: [
{
field: "date",
displayName: "Date",
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty(col.field)}}</span></div>',
width: 100
},
{
field: "amount",
displayName: "Amount",
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty(col.field)}}</span></div>'
},
{
field: 'comment',
displayName: 'Comment',
cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{row.getProperty(col.field)}}</span></div>',
}
],
$scope.refresh = function () {
var p = {
name: $scope.filterOptions.filterText,
pageNumber: (allPages >= $scope.pagingOptions.currentPage) ? $scope.pagingOptions.currentPage : $scope.pagingOptions.currentPage = 1,
pageSize: $scope.pagingOptions.pageSize,
sortInfo: sb.join("")
};
$http({
url: "reports/insurer_payments.json",
method: "GET",
params: p
}).success(function (data, insurer_payment) {
$scope.totalServerItems = data.insurerPaymentsCount;
$scope.insurer_payments_count = data.total_insurer_payments_count;
$scope.insurer_payments = data.insurer_payments;
$scope.insurer_payment = data.insurer_payment;
if (insurer_payment) {
$scope.insurer_payment = $filter('orderBy')($scope.insurer_payments, 'name')[0];
} else {
$scope.insurer_payment = $filter('filter')($scope.insurer_payments, {name: insurer_payment.name})[0];
}
if ($scope.insurer_payments) $scope.insurer_payment.selected = true;
$scope.showContent = true;
if ($scope.gridOptions.ngGrid) {
$scope.gridOptions.ngGrid.buildColumns();
}
}).error(function () {
});
}, 100);
};
$scope.selectInsurerPayment = function(item){
angular.forEach($scope.insurer_payments, function(item) {
item.selected = false;
});
$scope.insurer_payment = item;
$scope.insurer_payment.selected = true;
};
$scope.refresh();
}]);
A part of a view:
<a ng-repeat="insurer_payment in insurer_payments | orderBy:'name'"
class="list-group-item m-l"
ng-class="{'select m-l-none': insurer_payment.selected }"
ng-click="selectInsurerPayment(insurer_payment)">
<span class="block text-ellipsis m-l-n text-md" ng-class="{'m-l-none': insurer_payment.selected }">
{{ insurer_payment.name }}
</span>
</a>
<div class="well well-sm">
<div class="row">
<div class="col-sm-4">
<strong>Commission: {{insurer_payment.commission}}</strong>
</div>
<div class="col-sm-4">
<strong>Insurer Ppayment: {{insurer_payment.insurer_payment}}</strong>
</div>
<div class="col-sm-4">
<strong>Inequality: {{insurer_payment.commission - insurer_payment.insurer_payment}}</strong>
</div>
</div>
</div>
<div class="table-responsive">
<div ng-grid="gridOptions" class="gridStyle">
</div>
</div>
And a part of a rails controller:
def index
insurer_payments = current_company.insurers.map do |insurer|
{
commission: insurer.contracts.pluck(:commission).sum.to_f,
name: insurer.name,
insurer_payment: insurer.insurer_payments.pluck(:amount).sum.to_f,
id: insurer.id
}
end
insurer_payment = current_company.insurers.map do |insurer|
{
amount: insurer.insurer_payments.pluck(:amount).map { |x| x.to_f },
comment: insurer.insurer_payments.pluck(:comment),
date: insurer.insurer_payments.pluck(:date),
id: insurer.id
}
end
total_insurer_payments_count = current_company.insurers.map do |insurer|
insurer.insurer_payments.count
end
insurer_payments_count = current_company.insurer_payments.count
respond_to do |format|
format.json { render json: { insurer_payments: insurer_payments, insurer_payment: insurer_payment,
total_insurer_payments_count: total_insurer_payments_count,
insurerPaymentsCount: insurer_payments_count } }
end
end
So, how it can be done, by selecting an insurer to see the corresponding data?
I am not sure on this, since I don't have all of your code, but you may want to try some of the changes I have below.
Because ng-repeat has it's own scope, iterating through insurer_payment in insurer_payments is conflicting with insurer_payment on scope. When you loop through the insurer_payments, you are modifying the value of insurer_payment each time.
I would change
$scope.gridOptions = {
data: "insurer_payment",
to
$scope.gridOptions = {
data: [];
Since the data is an array, not a string.
Within the success callback of $http, you need to set gridOptions.data (unless this is elsewhere, I don't see where the grid is)
.success(function (data, insurer_payment) {
$scope.gridOptions.data = data;
...
}
And the selectInsurerPayment function:
$scope.selectInsurerPayment = function(item){
angular.forEach($scope.insurer_payments, function(item) {
item.selected = false;
});
$scope.selectedInsurerPayment = item;
$scope.insurer_payment.selected = true;
};
And finally, in the well in your HTML, change references to insurer_payment to selectedInsurerPayment, ex:
<strong>Commission: {{selectedInsurerPayment.commission}}</strong>
Old Solution
In ng-repeat:
ng-click="selectInsurerPayment(insurer_payment)"
to
ng-click="selection.insurer_payment = insurer_payment"
In the well,
<div class="well well-sm">
to
<div class="well well-sm" ng-if="selection.insurer_payment">
and change the references to insurer_payment to selection.insurer_payment.{variable}, example:
<strong>Commission: {{selection.insurer_payment.commission}}</strong>

Data Store using $resource, $cacheFactory with errorHandlingDirective

Learning AngularJS and trying to create a SPA with a data store for a
REST server. To reduce the traffic as much as possible, I want to
cache the data whenever possible. In the case of an error response
from the server, I would like to handle in one common directive for all callbacks. This would allow me to the directive across several controllers in a common way.
This post all works except the $emit and/or $broadcast are not
firing off the event that the directive is waiting $on. If it was working the template in the Directive will have the error description and be displayed on the HTML page when isError becomes true. At least that is my present thinking...
Plunker
My sample HTML file:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"> </script>
<script data-require="angular-resource#1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular-resource.js"></script>
<!--script src="app.js"></!--script-->
</head>
<body ng-controller="MainCtrl">
<h1>Hello Plunker!</h1>
{{data}}
<br />
<br />
isError: <error></error>
<br /><br />
Cached Data: {{dataCache}}
<br /><br />
<button ng-click="getData()">Data Callback</button>
<br /><br /><br />
<button ng-click="getError()">Callback Error</button>
<br /><br /><br />
Cache Info: {{oDataServiceInfo}}<br />
<button ng-click="resetCache()">Reset Cache</button>
</body>
</html>
My sample Controller:
var app = angular.module('app', ['ngResource']);
app.controller('MainCtrl', ['$scope', '$rootScope', 'loDataService', function ($scope,$rootScope, loDataService) {
$scope.getData = function () {
loDataService.getData(function (data) {
$scope.dataCache = loDataService.lCache
$scope.oDataServiceInfo = loDataService.oInfo;
$scope.data = data;
}, function (error) {
console.log(error);
})
};
$scope.getError = function () {
loDataService.getError(function (data) {
$scope.dataCache = loDataService.lCache
$scope.oDataServiceInfo = loDataService.oInfo;
$scope.data = data;
}, function (error) {
$rootScope.$broadcast("resourceError", error);
console.log(error);
})
};
$scope.resetCache = function () {
loDataService.resetCache();
$scope.oDataServiceInfo = loDataService.oInfo;
};
}]);
My sample data store:
app.factory('loDataService', ['$resource','$cacheFactory','$rootScope', function ($resource, $cacheFactory, $rootScope) {
var dbcCache = $cacheFactory('loDataService');
var oDBC = $resource('/', {},
{
'GetError': { url:'nonExistingConnection',method: 'GET' },
'GetData': { url: 'sampleData.json', method: 'GET', isArray: false }
});
return {
lCache: true,
oInfo: {},
resetCache: function () {
dbcCache.removeAll();
this.oInfo = dbcCache.info();
},
getData: function (callback, callbackError) {
_this = this;
var markets = dbcCache.get('Markets');
if (!markets) {
// fetch from server
_this.lCache = false;
oDBC.GetData(function (response) {
// store in cache
dbcCache.put('Markets', response.Markets);
_this.oInfo = dbcCache.info();
// return response
callback(response.Markets);
},
function (error) {
// oh no, what went wrong?
callbackError(error);
});
} else {
// return the cache
_this.lCache = true;
callback(markets);
}
},
getError: function (callback, callbackError) {
_this = this;
var marketsX = dbcCache.get('MarketsX');
if (!marketsX) {
// fetch from server
_this.lCache = false;
oDBC.GetError(function (response) {
// store in cache
dbcCache.put('MarketsX', response.Markets);
// return response
callback(response.Markets);
},
function (error) {
// oh no, what went wrong?
callbackError(error);
$rootScope.$broadcast("resourceError", error);
});
} else {
// return the cache
_this.lCache = true;
callback(marketsX);
}
}
}
}]);
My sample Directive:
app.directive("resourceError", ['$rootScope', function ($rootScope) {
return {
restrict: 'E',
template: '<div class="alert-box alert" ng-show="isError" >Error!!!</div>',
link: function (scope) {
$rootScope.$on("resourceError", function (event, error) {
scope.isError = true;
console.log(error);
})
}
}
}]);
Here in my "sampleData.json" file.
{
"Markets": [{
"id": 1,
"name": "Downtown",
"eventday": "1/1/1991",
"active": true
}, {
"id": 2,
"name": "County",
"eventday": "2/2/1991",
"active": true
}, {
"id": 3,
"name": "Beach",
"eventday": "3/3/1991",
"active": false
}]
}
Any thoughts?

Angular UI Bootstrap modal result is undefined

I'm building an app that loads a modal on a click on a button in an ng-grid row. Displaying the modal and the correct data works great. Problem is with getting the data back form the form in the modal. This bit of code
modalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
});
Returns 'undefined' for 'selectedItem'
Here's the modal.
<div ng-app="myApp">
<div ng-controller="UsersCtrl">
<script type="text/ng-template" id="editUserModal.html">
<div class="modal-header">
<h3 class="modal-title">Edit User <em>{{user.user_full_nm}} {{user.user_id}}</em></h3>
</div>
<div class="modal-body">
<p>User Name: <input type="text" name="user_full_nm" value="{{user.user_full_nm}}"></p>
<p>Email: <input type="text" name="user_nm" value="{{user.user_nm}}"></p>
<p>Active:
<select ng-model="user.deleted" ng-selected="user.deleted">
<option value="0" ng-selecte>Active</option>
<option value="1">Inactive</option>
</select>
</p>
<p>Termination Date: {{user.termination_date | date:'longDate'}}</p>
<p>Last Entry Date: {{user.last_entry | date:'longDate'}}</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<div class="gridStyle" ng-grid="gridOptions"></div>
</div>
</div>
Here's the Angular app.
var app = angular.module('myApp', ['ngGrid','ui.bootstrap']);
app.controller('UsersCtrl', function($scope, $http, $modal) {
$scope.filterOptions = {
filterText: "",
useExternalFilter: false
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [20, 40, 60],
pageSize: 20,
currentPage: 1
};
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.userData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('getUsers').success(function (largeLoad) {
data = largeLoad.filter(function(item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data,page,pageSize);
});
} else {
$http.get('getUsers').success(function (largeLoad) {
$scope.setPagingData(largeLoad,page,pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize,$scope.pagingOptions.currentPage,$scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage,
$scope.filterOptions.filterText);
}
}, true);
var editUserButtonTemplate = '<i class="fa fa-pencil" style="cursor:pointer;" ng-click="editUser(row.entity)"></i>';
$scope.gridOptions = {
data: 'userData',
columnDefs: [
{field: 'user_id', displayName: 'User ID', visible: false},
{field: 'user_nm', displayName: 'Email'},
{field: 'user_full_nm', displayName: 'Name'},
{field: 'deleted', displayName: 'Active', width: 60, cellFilter: 'activeFilter'},
{field: 'termination_date', displayName: 'Termination Date',cellFilter: 'date:\'longDate\''},
{field: 'last_entry', displayName: 'Last Entry Date',cellFilter: 'date:\'longDate\''},
{field: '', DisplayName: '', cellTemplate: editUserButtonTemplate, colFilterText: '', width:20}
],
enablePaging: true,
showFooter: true,
showFilter: true,
enableRowSelection: false,
filterOptions: $scope.filterOptions,
totalServerItems:'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions
};
/************ open the edit user modal *********************/
$scope.editUser = function(value) {
var modalInstance = $modal.open({
templateUrl: 'editUserModal.html',
// scope: $scope,
controller: 'editUserCtrl',
resolve: {
user: function () {
return value;
}
}
});
modalInstance.result.then(function(selectedItem){
$scope.selected = selectedItem;
});
};
});
app.controller('editUserCtrl', function($scope, $http, $modalInstance, user) {
$scope.user = user;
$scope.ok = function () {
$modalInstance.close($scope.selected);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
// for the 'deleted' column, display 'Active' or 'Inactive' instead of 1 or 0
app.filter('activeFilter', function(){
var types = ['Active', 'Inactive'];
return function(type){
return types[type];
};
});
So as happens so often, as soon as I posted my question I found this one.
angular-ui-bootstrap modal not passing back result
Which led me to the problem.
$scope.ok = function () {
$modalInstance.close($scope.selected);
};
Changed $scope.selected to $scope.user and it's working as expected now.

How do I use ng-grid with Angular HotTowel

I am using John Papa's Angular HotTowel and I don't know how to incorporate Angulars ng-grid into the html. Here is what I've added thanks to wonderful help from stondo. Breeze seems to be adding extra information that is no allowing ng-grid to render the data in the grid. Is there a way to strip the extra info that breeze sends or a work around for ng-grid to behave correctly with breeze data?
angular.module('app').controller(controllerId,
['common', 'datacontext','$scope', '$http', grid2]);
function grid2(common, datacontext, $scope, $http) {
.....
.....
} else {
$http.get('/breeze/Breeze/NoBadgePersonnels').success(function (largeLoad) {
$scope.setPagingData(largeLoad, page, pageSize);
});
activate();
function activate() {
common.activateController([mockData()], controllerId)
.then(function() { log('Activated Grid View'); });
function mockData() {
return datacontext.getEmployeePartialsNoBadges().then(function (data) {
return vm.grid2 = data.results;
});
}
}
Additional information
Datacontext.js looks as follows:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId,
['common', 'config', 'entityManagerFactory', datacontext]);
function datacontext(common, config, emFactory ) {
var EntityQuery = breeze.EntityQuery;
var getLogFn = common.logger.getLogFn;
var log = getLogFn(serviceId);
var logError = getLogFn(serviceId, 'error');
var logSuccess = getLogFn(serviceId, 'success');
var manager = emFactory.newManager();
var $q = common.$q;
var service = {
getPeople: getPeople,
getMessageCount: getMessageCount,
getEmployeePartials: getEmployeePartials,
getEmployeePartialsNoBadges: getEmployeePartialsNoBadges
};
var entityNames = {
personnel: 'Personnel'
};
return service;
function getEmployeePartialsNoBadges() {
var orderBy = 'lname';
var employees; //variable to hold employees once we get them back
//use query using Employees resource
return EntityQuery.from('NoBadgePersonnels')
.select('id, fname, lname, class, zip, cntySnrDte')
.orderBy(orderBy)
.toType('Personnel')
.using(manager).execute()
.then(querySucceeded, _queryFailed)
function querySucceeded(data) {
employees = data.results;
log('Retrieved [Employee Partials] from remote data source', employees.length, true);
//log('Retrieved [Employee Partials] from remote data source');
return employees;
}
}
function _queryFailed(error) {
var msg = config.appErrorPrefix + 'Error retrieving data from entityquery' + error.message;
logError(msg, error);
throw error;
}
=================================
It seems like the grid sees 5 items that I queried for, however the items don't want to display on the cells. Red arrow indicates that it allocated 5 rows, and green arrow indicates that I have selected one of the rows. Still doesn't display the records.
thanks
nick
I had to modify John Papa's Hottowel.Angular template, because it wasn't working as expected with latest angular/breeze versions. I'll later share a github link and a blog post about that.
I was able to get ng-grid working just adding $scope and $http to the controller. Read the comment inside the code block to see how it could be entirely done without inject $http.
(function () {
'use strict';
var controllerId = 'corrieri';
angular.module('app').controller(controllerId, ['common', 'datacontext', '$scope', '$http', corrieri]); //'$http', '$scope',
function corrieri(common, datacontext, $scope, $http) { //,$http, $scope
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
$scope.corrieriList = [];
vm.corrieri = [];
vm.news = {
title: 'Corrieri',
description: 'Lista Corrieri'
};
vm.title = 'Corrieri';
//ng-grid test
$scope.filterOptions = {
filterText: "",
useExternalFilter: false
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [10, 20, 30],
pageSize: 10,
currentPage: 1
};
$scope.setPagingData = function (data, page, pageSize) {
data = data.map(function (item) {
return {
PK_ID: item.PK_ID,
Ragione_Sociale: item.Ragione_Sociale,
Telefono: item.Telefono,
Nazionalita: item.Nazionalita,
Indirizzo: item.Indirizzo,
Cap: item.Cap,
Provincia: item.Provincia,
Descrizione: item.Descrizione
};
});
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.corrieriList = pagedData; //.results;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('breeze/Corrieri/GetCorrieri').success(function (largeLoad) {
var myModArray = largeLoad.map(function (item) {
return {
Pk_ID: item.Pk_ID,
Ragione_Sociale: item.Ragione_Sociale,
Telefono: item.Telefono,
Nazionalita: item.Nazionalita,
Indirizzo: item.Indirizzo,
Cap: item.Cap,
Provincia: item.Provincia,
Descrizione: item.Descrizione
};
});
data = myModArray.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data, page, pageSize);
});
} else {
$http.get('breeze/Corrieri/GetCorrieri').success(function (largeLoad) {
$scope.setPagingData(largeLoad, page, pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.gridOptions = {
data: 'corrieriList',
enablePaging: true,
showFooter: true,
showFilter: true,
enableCellEdit: true,
enableColumnResize: true,
enableColumnReordering: true,
pinSelectionCheckbox: true,
totalServerItems: 'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions
};
//ng-grid test end
activate();
function activate() {
var promises = [getCorrieri()];
common.activateController(promises, controllerId)
.then(function () {
log('Activated Corrieri View');
});
}
//This function was used to get data using Breeze Controller
//and I was even able to use it to bind data to ng-grid
//calling the function getCorrieri inside my controller and binding
//gridOptions data to vm.corrieri or just the name of the function (in my case getCorrieri)
// $scope.gridOptions = { data: getCorrieri}
//Be aware that since we r using a Breeze Controller data retrieved have additional
//informations, so we have to remove those, if we bind using vm.corrieri.
//I found it easier to implement paging using $http and $scope, even though I think
//I could do it using only $scope and breeze.
//getCorrieri().then(function() {
// angular.forEach(vm.corrieri, function (cor) {
// delete cor._backingStore['$id'];
// delete cor._backingStore['$type'];
// $scope.corrieriList.push(cor._backingStore);
// });
//});
function getCorrieri() {
return datacontext.getCorrieri().then(function (data) {
return vm.corrieri = data.results;
});
}
}
})();
Below you can find my html for reference. Make sure to surround your's ng-grid div with data-ng-controller or just ng-controller='corrieri'
<section id="corrieri-view" class="mainbar" data-ng-controller="corrieri as vm">
<section class="matter">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="widget wgreen">
<div data-cc-widget-header title="Corrieri" allow-collapse="true"></div>
<div class="widget-content text-center text-info">
<div data-ng-controller='corrieri'>
<div class="gridStyle col-md-12" ng-grid="gridOptions">
</div>
</div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
Btw, don't forget to add 'ngGrid' to your modules list in app.js
var app = angular.module('app', ['ngGrid', other modules])
and also include ng-grid css and js in index.html (that is obvious, but better safe than sorry)
I struggled a few days to get this working properly, so I hope to help anyone out there having the same problem.
Try this out:
angular.module('app').controller(controllerId, ['common', 'datacontext', '$scope', grid]);
function grid(common, datacontext, $scope) {
$scope.gridOptions = {
data: 'vm.employees'
};
activate();
function activate() {
common.activateController([getEmployees()], controllerId)
.then(function () { log('Activated Grid View'); });
}
//get data for employees
function getEmployees() {
return datacontext.getEmployeePartialsNoBadges().then(function (mydata) {
return vm.employees = data;
});
}
}
here is an image of what I see
and here is the code I changed:
function getEmployees() {
return datacontext.getEmployeePartialsNoBadges().then(function (mydata) {
log(JSON.stringify(mydata));
return vm.employees = mydata.data;
});
Here is some additional info showing the data is coming through. Remote data source shows 1496 records. The preview for /breeze/breeze show data. I've blanked out sensitive info.
Here is the getEmployeePartialsNoBadges() method in my datacontext that was using entity framework:
function getEmployeePartialsNoBadges() {
var orderBy = 'lname';
var employees; //variable to hold employees once we get them back
//use query using Employees resource
return EntityQuery.from('NoBadgePersonnels')
.select('id, fname, lname, class, zip, cntySnrDte')
.orderBy(orderBy)
.toType('Personnel')
.using(manager).execute()
.then(querySucceeded, _queryFailed)
function querySucceeded(data) {
employees = data.results; //fillup the variable for employee with results
log('Retrieved [Employee Partials] from remote data source', employees.length, true);
//log('Retrieved [Employee Partials] from remote data source');
return employees;
}
}
============================== Nick ==============================
This is what my new mockup looks like now and I put this in datacontext calling it getPeople:
function getPeople() {
var people = [
{ firstName: 'John', lastName: 'Papa', age: 25, location: 'Florida' },
{ firstName: 'Ward', lastName: 'Bell', age: 31, location: 'California' },
{ firstName: 'Colleen', lastName: 'Jones', age: 21, location: 'New York' },
{ firstName: 'Madelyn', lastName: 'Green', age: 18, location: 'North Dakota' },
{ firstName: 'Ella', lastName: 'Jobs', age: 18, location: 'South Dakota' },
{ firstName: 'Landon', lastName: 'Gates', age: 11, location: 'South Carolina' },
{ firstName: 'Haley', lastName: 'Guthrie', age: 35, location: 'Wyoming' }
];
return $q.when(people);
}
I have reworked html and controller code to clean things up. The html is now call grid2.html and the controller is called grid2.js
(function () {
'use strict';
var controllerId = 'grid2';
angular.module('app').controller(controllerId,
['common', 'datacontext','$scope', grid2]);
function grid2(common, datacontext, $scope) {
var vm = this;
vm.grid2 = [];
$scope.gridOptions = {
data: 'vm.grid2'
};
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
vm.activate = activate;
vm.title = 'Grid2';
activate();
function activate() {
common.activateController([mockData()], controllerId)
.then(function() { log('Activated Grid View'); });
function mockData() {
return datacontext.getPeople().then(function (mydata) {
log(JSON.stringify(mydata));
return vm.grid2 = mydata.data;
});
}
}
}
})();
controller grid2.js
<section class="mainbar" data-ng-controller="grid2 as vm">
<section class="matter">
<div class="container">
<div class="row">
<div class="widget wgreen">
<div data-cc-widget-header title="Grid 2"></div>
<div class="widget-content user">
</div>
this is grid2 test
<div class="gridStyle" ng-grid="gridOptions"></div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</section>
Here what the screen looks like now. still no data in the grid:
In the debug, the data property shows undefined still
The mydata does contain array of data
The vm is an empty array on the return statement
The vm.grid becomes empty after the return and I'm unsure what the vm is also
The console show data being present

Resources