Angular UI Grid onRegisterApi method call twice - javascript

Here in my code if I run this independently it works fine, but after integrate in my project the "onRegisterApi" method call twice. It seems some conflict with existing Ui-Grid.
Can Anyone have any idea? How to debug this and find the root cause. I already spend so much time on this
var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.pagination']);
app.controller('MainCtrl', [
'$scope', '$http', 'uiGridConstants', function($scope, $http, uiGridConstants) {
var paginationOptions = {
pageNumber: 1,
pageSize: 25,
sort: null
};
$scope.gridOptions = {
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
useExternalPagination: true,
useExternalSorting: true,
columnDefs: [
{ name: 'name' },
{ name: 'gender', enableSorting: false },
{ name: 'company', enableSorting: false }
],
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
if (sortColumns.length == 0) {
paginationOptions.sort = null;
} else {
paginationOptions.sort = sortColumns[0].sort.direction;
}
getPage();
});
gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNumber = newPage;
paginationOptions.pageSize = pageSize;
getPage();
});
}
};
var getPage = function() {
// server call
};
getPage();
}
]);

Related

AngularJS: ng-click not working in ui-grid cellTemplate

Here I go again, with angular problems.
I have a grid in my HTML, which is just a line.
I'm copypasteing the controller.
app.controller('PanelController', function ($scope, $compile, uiGridConstants){
var actionTemplate = '<div class="ui-grid-cell-contents"><img class="addNotes" src="images/button/detail.gif" ng-click="dettaglio(row.entity)" /></div>';
$scope.dettaglio = function(ritornoSearch, inspect) {
console.log("make it function");
};
columnDefs: [
{ field: 'azioni', enableFiltering: false, width: 85, enableSorting: false, enableColumnMenu: false, cellTemplate: actionTemplate, displayName: 'Azioni'},
{ field: 'codeSubInstaller', headerCellClass: $scope.highlightFilteredHeader },
{ field: 'nomeSubInstaller', headerCellClass: $scope.highlightFilteredHeader },
{ field: 'cognSubInstaller', headerCellClass: $scope.highlightFilteredHeader },
{ field: 'codeFiscaleSubInstaller', headerCellClass: $scope.highlightFilteredHeader },
{ field: 'descStato' , headerCellClass: $scope.highlightFilteredHeader }
]
};
The question is: when I open it in my browser, the image doens't show up as clickable. If I try to click on it anyway, it doens't even provide me the console.log.
What am I missing?
Just do it like its documented in http://ui-grid.info/docs/#/tutorial/305_appScope and compare this runnable plnkr demo with your solution.
$scope.grid.appScope is available in all templates that the grid uses.
In a template, you access the scope using grid.appScope property
In that way you need to change your template into the right syntax:
ng-click="grid.appScope.dettaglio(row)":
var actionTemplate = '<div class="ui-grid-cell-contents"><img class="addNotes" src="images/button/detail.gif" ng-click="grid.appScope.dettaglio(row)" /></div>';
AngularJS application example with ui-grid:
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$scope', '$log', '$http', function ($scope, $log, $http) {
$scope.dettaglio = function (row) {
console.log(row);
alert('inside');
};
$scope.gridOptions = {};
$scope.gridOptions.columnDefs = [
{name: 'name'},
{name: 'gender'}, {
name: 'ShowScope',
cellTemplate: '<button class="btn primary" ng-click="grid.appScope.dettaglio(row)">Click Me</button>'
}
];
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json').success(function (data) {
$scope.gridOptions.data = data;
});
}]);

Angular: updating view with value passed from directive to controller

Budding web developer here struggling with updating the view from my controller.
I'm using highmaps and angular to build a neat selection tool for my web app. I've got a directive nested inside the scope of a controller. I would like this directive to update a value (selectedCountry) stored in the controller. Then, I'd like the controller to display the up to date selectedCountry value on the view.
I've checked that the directive is passing the correct selectedCountry value to the parent controller. However, the controller is not updating the view to match the updated value. I would greatly appreciate if someone could take a look at this.
Demo Here: http://jsfiddle.net/frauLLmr/5/
index.html
<div ng-app="myApp">
<div ng-controller="GraphController as graphCtrl">
<div> {{graphCtrl.showSelectedCountry()}} </div>
<div> {{graphCtrl.selectedCountry}} </div>
<high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
</div>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function() {
var self = this;
self.selectedCountry = 'unselected';
var outsideScopeTest = function() {
alert('selectedCountry (from controller scope): '
+ self.selectedCountry);
};
self.updateSelectedCountry = function(newCountry) {
self.selectedCountry = newCountry;
outsideScopeTest();
};
self.showSelectedCountry = function() {
return self.selectedCountry;
};
});
myApp.directive('highChartDirective', function () {
return {
restrict: 'E',
scope: {
updateSelectedCountry: '&'
},
link: function(scope, element) {
Highcharts.mapChart(element[0], getMapOptions(mapClick));
function mapClick(event) {
scope.updateSelectedCountry({newCountry: event.point.name});
alert('selectedCountry (from directive scope): '
+ event.point.name);
}
}
};
function getMapOptions(callback) {
return {
title: {
text: ''
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
series: [{
data: getTestCountries(),
mapData: Highcharts.maps['custom/world-highres'],
// TODO-chantelle: figure out how geoJSON joinBy works
joinBy: 'hc-key',
name: 'Emission per capita',
states: {
hover: {
color: '#9370DB'
}
},
dataLabels: {
enabled: false,
format: '{point.name}'
}
}],
plotOptions: {
series: {
events: {
click: function(event) {
callback(event);
}
}
}
}
};
}
function getTestCountries() {
return [{
"hc-key": "ca",
"value": 0
}, {
"hc-key": "br",
"value": 1
}, {
"hc-key": "ru",
"value": 2
}];
}
});
the issue is that Highcharts.mapChart(element[0], getMapOptions(mapClick)); is not part of the angular scope. So any calls here will not trigger the angular app to refresh. You need to force angular to update using $scope.apply();
var outsideScopeTest = function() {
alert('selectedCountry (from controller scope): '
+ selfc.selectedCountry);
// force angular update
$scope.$apply();
};
Try this
<div ng-app="myApp">
<div ng-controller="GraphController as graphCtrl">
<div> {{graphCtrl.showSelectedCountry()}} </div>
<div> {{graphCtrl.selectedCountry}} </div>
<high-chart-directive update-selected-country='graphCtrl.updateSelectedCountry(newCountry)'></high-chart-directive>
</div>
</div>
the js
var myApp = angular.module('myApp', []);
myApp.controller('GraphController', function($scope) {
var self = this;
self.selectedCountry = 'unselected';
var outsideScopeTest = function() {
alert('selectedCountry (from controller scope): '
+ self.selectedCountry);
$scope.$apply();
};
self.updateSelectedCountry = function(newCountry) {
self.selectedCountry = newCountry;
outsideScopeTest();
};
self.showSelectedCountry = function() {
return self.selectedCountry;
};
});
myApp.directive('highChartDirective', function () {
return {
restrict: 'E',
scope: {
updateSelectedCountry: '&'
},
link: function(scope, element) {
Highcharts.mapChart(element[0], getMapOptions(mapClick));
function mapClick(event) {
scope.updateSelectedCountry({newCountry: event.point.name});
alert('selectedCountry (from directive scope): '
+ event.point.name);
}
}
};
function getMapOptions(callback) {
return {
title: {
text: ''
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
series: [{
data: getTestCountries(),
mapData: Highcharts.maps['custom/world-highres'],
// TODO-chantelle: figure out how geoJSON joinBy works
joinBy: 'hc-key',
name: 'Emission per capita',
states: {
hover: {
color: '#9370DB'
}
},
dataLabels: {
enabled: false,
format: '{point.name}'
}
}],
plotOptions: {
series: {
events: {
click: function(event) {
callback(event);
}
}
}
}
};
}
function getTestCountries() {
return [{
"hc-key": "ca",
"value": 0
}, {
"hc-key": "br",
"value": 1
}, {
"hc-key": "ru",
"value": 2
}];
}
});

ui-grid enableSelectAll and paginationPageSize

I have a grid and I would like giving a pagination size of 10, I want to select all options to restrict row selection to only 10, but given this configuration, it selects entire data set across all pages.
$scope.gridEvents = {
enableSorting : true,
enableSelectAll: true,
enableColumnResize: true,
enablePaginationControls: false,
rowHeight: 27,
enableScrollbars : true,
paginationPageSize : 10
}
any help is appreciated
Please try as shown below.
Working Plunker
JS
$scope.gridOptions = {
paginationPageSizes: [10, 20, 30],
paginationPageSize: 10,
useExternalPagination: true,
enableRowSelection: true,
enableSelectAll: true,
totalItems: 100,
columnDefs: [
{ name: 'name' },
{ name: 'gender' },
{ name: 'company' }
],
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
$scope.gridApi.pagination.on.paginationChanged( $scope, function( currentPage, pageSize){
$scope.getPage(currentPage, pageSize);
});
}
};
$scope.getPage = function(pageNumber, pageSize){
var startingRow = pageSize * ( pageNumber - 1); // page number starts at 1, not zero
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function (data) {
var newData = [];
for( var i = startingRow; i < startingRow + $scope.gridOptions.paginationPageSize; i++ ) {
newData.push( data[i] );
}
$scope.gridOptions.data = newData;
});
};
$scope.getPage(1, 10);
Html
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid"></div>

Angular JS ui-grid cellTemplate's ng-click not firing when scope function tries to pass the cell info as params

I can't seem to get ng-click to fire for me and I've been trying for hours. I've read a bunch of similar issues on SO, but none seem to fix my issue. Note that if I change ng-click to onclick the event fires.
My JS:
var app = angular.module('app', ['ngTouch', 'ngAnimate', 'ui.grid', 'ui.grid.moveColumns', 'ui.grid.resizeColumns']);
app.controller('matterController', ['$scope', '$http', 'uiGridConstants', function ($scope, $http, uiGridConstants) {
var industryFields,
departmentFields,
regionFields;
$scope.gridOptions = {
enableFiltering: true,
enableColumnResizing: true,
enableSorting: true,
columnDefs: [
{ name: 'Client_Name', width: 120, enableHiding: false },
{ name: 'Client_Number', width: 140, enableHiding: false },
{ name: 'Matter_Name', width: 130, enableHiding: false },
{ name: 'Matter_Number', width: 140, enableHiding: false },
{ name: 'Billing_Partner', width: 250, enableHiding: false },
{ name: 'Matter_Descriptions', width: 180, enableHiding: false
, cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#" ng-click="displayDescription(\'{{COL_FIELD}}\');">View Description</a></div>' },
{ name: 'Industries', width: 120, enableHiding: false },
{ name: 'Departments', width: 130, enableHiding: false },
{ name: 'Regions', width: 120, enableHiding: false }
],
showGroupPanel: true
};
function loadData() {
$http.get('api/ClientMatter/')
.success(function (data) {
$scope.gridOptions.data = data;
});
$http.get('Home/GetIndustries')
.success(function (data) {
industryFields = data;
});
$http.get('Home/GetDepartments')
.success(function (data) {
departmentFields = data;
});
$http.get('Home/GetRegions')
.success(function (data) {
regionFields = data;
});
}
$scope.displayDescription = function(data) {
alert(data);
}
loadData();
}]);
The "Matter_Descriptions" column has a custom cell template which needs to call the "displayDescription" method. So far I can't get it to fire at all.
My HTML:
<div class="screen-container" ng-controller="matterController">
<button onclick="location.href = '#Url.Action("Create", "Home")'; return false;" style="float: right;">New Matter</button>
<br/><br/>
<div id="home-grid" ui-grid="gridOptions" class="grid" ui-grid-move-columns ui-grid-resize-columns></div>
</div>
And here is a screen shot of the hyperlink at runtime showing the data exactly as I want it:
Pretty basic. Any help is appreciated! Thanks!
You DO NOT NEED BRACES because you are inside ng already when you apply ng-directive's:
<button ng-click = 'yourscopefn(yourscopevars,,)'>buttonface</button>
you don't do this :
<button ng-click = 'yourscopefn({{yourscopevars}},,)'>buttonface</button>
wrong!!
All you need to do for your ui-grid column def celltemplate is:
{ name: 'yourcolumn', cellTemplate:
' <a ng-href="#" ng-click="grid.appScope.yourfunction(COL_FIELD);">{{COL_FIELD}}</a>' }
I found the solution thanks to this post on SO: Button click does not work in Celltemplate angular grid
It turns out I needed to change:
ng-click="displayDescription(\'{{COL_FIELD}}\');
To:
ng-click=\'grid.appScope.displayDescription("{{COL_FIELD}}");
I couldn't tell you why this works, but my application is now working as expected. Thanks to those who commented.

ExtJS TaskRunner

I'm still in the learning process with EXTJS and any help would be much appreciated.
The goal for me is to load data into a grid where one cell needs to have the value incremented every minute. From my research using the TaskRunner function is the way to go but can't figure out where to put it and how to use it. My assumption is that it needs to go into the model or the controller but I'm not sure. In my simple project I'm using the MVC architecture.
Currently my gird works as expected. It reads in a file does a date conversion that produces a minute value. It's that minute value that I need to increment.
The code below is a sample TaskRunner snippit that I'm working with, right or wrong I don't know yet.
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
}),
interval: 60000 // 1-minute interval
});
task.start();
Model:
Ext.define("myApp.model.ActionItem", {
extend : "Ext.data.Model",
fields : [
{
name: 'pri',
type: 'int'
},
{
name: 'request',
type: 'int',
defaultValue: 0,
convert : function(v, model) {
return Math.round((new Date() - new Date(v)) / 60000);
}
}
]
});
Controller:
Ext.define("myApp.controller.HomeController", {
extend: "Ext.app.Controller",
id: "HomeController",
refs: [
{ ref: "ActionItemsGrid", selector: "[xtype=actionitemgrid]" },
{ ref: "DetailsPanel", selector: "[xtype=actionitemdetails]" }
],
pri: "",
models: ["ActionItem"],
stores: ["myActionStore"],
views:
[
"home.ActionItemDetailsPanel",
"home.ActionItemGrid",
"home.HomeScreen"
],
init: function () {
this.control({
"#homescreen": {
beforerender: this.loadActionItems
},
"ActionItemsGrid": {
itemclick: this.displayDetails
}
});
},
displayDetails: function (model, record) {
this.getDetailsPanel().loadRecord(record);
},
loadActionItems: function () {
var store = Ext.getStore("myActionStore");
store.load();
this.getActionItemsGrid().reconfigure(store);
}
});
View:
Ext.define("myApp.view.home.ActionItemGrid", {
extend: "Ext.grid.Panel",
xtype: "actionitemgrid",
resizable: true,
multiSelect: false,
enableDragDrop : false,
store: null,
columns:
[
{ header: "Pri", dataIndex: "pri", sortable: false, autoSizeColumn: true},
{ header: "Req", dataIndex: "request", sortable: false, autoSizeColumn: true}
],
viewConfig:
{
listeners: {
refresh: function(dataview) {
Ext.each(dataview.panel.columns, function(column) {
if (column.autoSizeColumn === true)
column.autoSize();
})
}
}
}
});
Sample JSON File:
{
"actionitems" : [
{
"pri": 1,
"request": "2014-12-30T03:52:48.516Z"
},
{
"pri": 2,
"request": "2014-12-29T05:02:48.516Z"
}
]
}
You have error in code which creates task - you should provide function to run configuration property, not result of invocation. Try this:
var runner = new Ext.util.TaskRunner();
var task = runner.newTask({
run: function() {
store.each(function (item)
{
var incReq = item.get('request') + 1;
item.set('request', incReq);
})
},
interval: 60000 // 1-minute interval
});
task.start();
You can put that code in loadActionItems method.

Categories

Resources