ng-grid afterSelectionChange return value - angularjs

it's possible to afterSelectionChange return value with ng-grid ???
how can I accomplish it? I want to get $scope.programEdit value,
setPagingData function to set data show on view ,
getPagedDataAsync function to get value with $resource
anyone ideas ?
please help
$scope.setPagingData = function(data, page, pageSize, type){
var array = [];
for(var key in data){
if(!data.hasOwnProperty(key)){
continue;
}
array.push(key, data[key])
}
if(type == 0){
var a = array.slice(1,4);
$scope.myData = a[0];
}else{
var a = array.slice(1);
$scope.myData = a;
}
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
return $scope.myData
};
$scope.getPagedDataAsync = function (pageSize, page, searchText, type) {
setTimeout(function () {
var data;
programService.query({
page: page
}, function (result) {
data = {
'program': result
};
$scope.setPagingData(data,page,pageSize,0)
return data
});
}, 100);
};
$scope.gridOptions = {
data: 'myData',
enablePaging: true,
showFooter: true,
totalServerItems:'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions,
selectedItems: $scope.mySelections,
multiSelect: false,
afterSelectionChange: function ($routeParams, $location, programService) {
$scope.program = $scope.mySelections[0];
var id = $scope.mySelections[0].programId;
if ($scope.mySelections[0].programId) {
$scope.programEdit = {
'program': programService.get({
page: 1,
id: $scope.mySelections[0].programId
})};
}
}
};
I want to get it to show on edit html
<form ng-submit="save()">
<input type="hidden" ng-model="programEdit.programId"/>
<dl>
<dt>Program Name</dt>
<dd><input name="programName" type="text" ng-model="programEdit.programName"/></dd>
</dl>
<div class="form-actions">
<button type="submit">Save</button>
</div>
</form>

$scope.programEdit should contain programId and programName (something like $scope.programEdit = {programId: 11, programName: 'Hello'} but what you do is setting programService.get to a property named program.
What you should do, assuming that programService.get is a promise, and that it returns a JSON object with the data then you should do something like that:
programService.get({ page: 1, id: $scope.mySelections[0].programId }).success(function(data) {
$scope.programEdit = {programName: data.programName, programId: data.programId};
});

Related

select2 tags with restangular response

How would I pass tags to select2 if the object comes from restfull API using restangular
So I have the following markup
<input type="hidden" ui-select2="select2Options" style="width:100%" ng-model="list_of_string">
returned restangular data
[
{"count":"13","brand":"2DIRECT GMBH"},
{"count":"12","brand":"3M DEUTSCHLAND GMBH"},
{"count":"1","brand":"a-rival"}
]
and here is my Controller method
var filterProducts = function($scope, api) {
api.categories().then(function(response) {
//this is the respose what I would like to use in select2 tags
$scope.brands = response;
});
$scope.list_of_string = ['tag1', 'tag2']
$scope.select2Options = {
'multiple': true,
'simple_tags': true,
'tags': ['tag1', 'tag2', 'tag3', 'tag4'] // Can be empty list.
};
};
Update
Finally I managed
and the hole looks like
$scope.select2Options = {
data: function() {
api.categories().then(function(response) {
$scope.data = response;
});
return {'results': $scope.data};
},
'multiple': true,
formatResult: function(data) {
return data.text;
},
formatSelection: function(data) {
return data.text;
}
}
var filterProducts = function($scope, api) {
api.categories().then(function(response) {
//this is the respose what I would like to use in select2 tags
$scope.brands = response;
$scope.select2Options.tags = response;
});
Hope this will help..

How to manually add a datasource to Angularjs-select2 when select2 is set up as <input/> to load remote data?

I am using the Select2 as a typeahead control. The code below works very well when the user types in the search term.
However, when loading data into the page, I need to be able to manually set the value of the search box.
Ideally something like: $scope.selectedProducerId = {id:1, text:"Existing producer}
However, since no data has been retrieved the Select2 data source is empty.
So what I really need to be able to do is to add a new array of data to the datasource and then set the $scope.selectedProducerId, something like: $scope.producersLookupsSelectOptions.addNewData({id:1, text:"Existing producer}) and then
$scope.selectedProducerId = 1;
Researching this I have seen various suggestions to use initSelection(), but I can't see how to get this to work.
I have also tried to set createSearchChoice(term), but the term is not appearing in the input box.
I would be most grateful for any assistance.
Thanks
This is the html
<div class="col-sm-4">
<input type="text" ui-select2="producersLookupsSelectOptions" ng- model="selectedProducerId" class="form-control" placeholder="[Produtor]" ng-change="selectedProducerIdChanged()"/>
</div>
This is the controller
angular.module("home").controller("TestLookupsCtrl", [
"$scope", "$routeParams", "AddressBookService",
function($scope, $routeParams, AddressBookService) {
$scope.producersLookupsSelectOptions = AddressBookService.producersLookupsSelectOptions();
}
]);
This is the service:
angular.module("addressBook").service("AddressBookService", [
"$http", "$q", function($http, $q) {
var routePrefix = "/api/apiAddressBook/";
//var fetchProducers = function(queryParams) {
// return $http.get(routePrefix + "GetClientsLookup/" + queryParams.data.query).then(queryParams.success);
//};
var _getSelectLookupOptions = function(url, minimumInputLength, idField, textField) {
var _dataSource = [];
var _queryParams;
return {
allowClear: true,
minimumInputLength: minimumInputLength || 3,
ajax: {
data: function(term, page) {
return {
query: term
};
},
quietMillis: 500,
transport: function(queryParams) {
_queryParams = queryParams;
return $http.get(url + queryParams.data.query).success(queryParams.success);
},
results: function(data, page) {
var firstItem = data[0];
if (firstItem) {
if (!firstItem[idField]) {
throw "[id] " + idField + " does not exist in datasource";
}
if (!firstItem[textField]) {
throw "[text] " + textField + " field does not exist in datasource";
}
}
var arr = [];
_.each(data, function(returnedData) {
arr.push({
id: returnedData[idField],
text: returnedData[textField],
data: returnedData
});
});
_dataSource = arr;
return { results: arr };
}
},
dataSource: function() {
return _dataSource;
},
getText: function (id) {
if (_dataSource.length === 0) {
throw ("AddressBookService.getText(): Since the control was not automatically loaded the dataSource has no content");
}
return _.find(_dataSource, { id: id }).text;
}
//initSelection: function(element, callback) {
// callback($(element).data('$ngModelController').$modelValue);
//},
//createSearchChoice:function(term) {
// return term;
//},
addNewData:function(data) {
this.ajax.results(data,1);
};
};
return {
producersLookupsSelectOptions: function() {
var url = routePrefix + "GetClientsLookup/";
return _getSelectLookupOptions(url, 2, "Id", "Name");
},
}
}
]);

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

AngularJS UI ng-grid not painting content text & blank when used inside directive

I am developing one SearchAndSelect control (AngularJS directive) which contains it's own ng-grid, slider page. Everything is working, data is being fetched, number of rows are coming to the grid, but grid is not showing text.
SearchAndSelectDirective.js
App.directive('searchAndSelect',
function () {
return {
restrict: 'E',
templateUrl: "/app/directives/searchAndSelect.html",
controller: "searchAndSelectController",
transclude: false,
scope: {
currentNode: '='
},
compile: function() {
// return true;
}
};
}
);
SearchAndSelect.html
<button class="btn" ng-click="openSliderPage()">Add/Remove {{EntityName}}</button>
<div id="divSlide" class="sliderDiv">
<div class="sliderHeader" ng-model="partialPageHeading">
<span class="sliderHeaderLabelOriginal">{{partialPageHeading}}</span>
</div>
<div>
<div class="gridStyle" ng-grid="gridOptions"></div>
<div class="modal-footer">
<input ng-model="filterOptions.filterText" />
<button class="btn btn-info" ng-click="getPagedDataAsync()">Filter</button>
<button class="btn btn-primary" ng-click="add()">Update</button>
<button class="btn btn-warning" ng-click="cancnel()">Cancel</button>
</div>
</div>
<!--<ng-include src="svcSliderView"></ng-include>-->
</div>
It has got it's own controller, which fetches the data in async manner. Number of rows are being generated within the grid, grid is visible. I have code inside controller to mark some rows selected, and it is happening. But only the content is not being displayed. If I see browser's element exploration, I can see the data is there.
SearchAndSelectController.js
$scope.filterOptions = {
filterText: "",
useExternalFilter: false
};
$scope.pagingOptions = {
pageSizes: [50, 100, 200],
pageSize: 50,
currentPage: 1
};
$scope.getVehListParams = function () {
var params = { PageNo: $scope.pagingOptions.currentPage, PageSize: $scope.pagingOptions.pageSize };
params.CalculateTotal = false;
if (!$scope.totalCount) {
params.CalculateTotal = true;
}
params.FilterText = '';
if ($scope.filterOptions.filterText) {
params.FilterText = $scope.filterOptions.filterText;
}
return params;
};
$scope.getPagedDataAsync = function () {
var vehListGetParams = $scope.getVehListParams();
seVehicleResource.get(vehListGetParams,
function (result) {
$scope.dataList = result.DataList;
if (result.TotalCount || result.TotalCount == 0) {
$scope.totalCount = result.TotalCount;
}
//mark already added rows in left as selected.
$timeout(function () {
if ($scope.planSelected) {
_.each($scope.planSelected.Vehicles, function (vehicle) {
var vIdx = $.map(result.DataList, function (obj, index) {
if (obj.VehicleId == vehicle.VehicleId) {
return index;
}
return null;
});
if (vIdx && vIdx.length > 0) {
$scope.vehicleExisted.push(result.DataList[vIdx[0]]);
$scope.gridOptions.selectItem(vIdx[0], true);
}
});
}
});
}, function (error) {
console.log(error);
});
};
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && (newVal.currentPage !== oldVal.currentPage || newVal.pageSize !== oldVal.pageSize)) {
$scope.getPagedDataAsync();
}
}, true);
$scope.allSelected = false;
$scope.gridOptions = {
data: 'dataList',
enablePaging: true,
showFooter: true,
showFilter: true,
columnDefs: [{ field: 'Make', displayName: 'Make', width: '35%' }, { field: 'Model', displayName: 'Model', width: '35%' }, { field: 'BeginYear', displayName: 'Begin Year', width: '15%' }, { field: 'EndYear', displayName: 'End Year', width: '15%' }],
totalServerItems: 'totalCount',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions.filterText,
showSelectionCheckbox: true,
afterSelectionChange: $scope.afterSelectionChange,
};
I used this directive inside following div, which made its fontsize to 0, removing this container grid, fixed my issue.
Thanks All
<div class="btn-group">

Resources