How to make checkbox cell edit template in ng-grid? - angularjs

I am new to ng-grid. I am learning ng-grid with edit template options. i have created grid with edit checkbox options.But i don't know How to get value in that grid after edit the checkbox? Thank you.
Here JSfiddle.
var myapp = angular.module('myapp', ["ui", "ngGrid"]);
myapp.controller('myctrl', function($scope, $http) {
$scope.testInfo= "TestInfo";
$scope.data = {
persons: [],
selected:[],
load: function () {
$http.get("/echo/json/").success(function(data) {
$scope.data.persons = [
{id:1, name:"Max", number:51323.512,value:'on'},
{id:2, name:"Adam", number:7245.2,value:'on'},
{id:3, name:"Betty", number:828,value:'off'},
{id:4, name:"Sara", number:23452.45182,value:'on'}
];
$scope.data.selected[0] = $scope.data.persons[0];
});
}
};
var cellTemplate = "<div ng-class=\"'ngCellText colt' + $index\">"
+ " <span ng-cell-text>{{COL_FIELD}}</span>"
+ "</div>";
var cellEditTemplate = '<input type="checkbox" ng-checked="row.entity.value==\'on\'" ng-input="COL_FIELD" /></div>';
$scope.grid = {
options: {
data: "data.persons",
selectedItems: $scope.data.selected,
multiSelect: false,
columnDefs: [
{field:"id", displayName:"ID"},
{field:"name", displayName:"Name"},
{field:"number", displayName:"Nummer", cellFilter:"number:2"},
{field: "value",displayName:"Value",enableCellEdit : true,cellTemplate : cellTemplate,
editableCellTemplate : cellEditTemplate}
]
}
};
});
<div ng-app="myapp">
<div ng-controller="myctrl">
<a class="btn" ng-click="data.load()">Get data!</a>
<div ng-grid="grid.options" class="grid"></div>
<ul ng-repeat="item in data.selected">
<li>{{item}}</li>
</ul>
</div>
</div>

You've probably already figured this out by now, but one possible options is to use ng-grids build in checkbox selector. It's not shown in the examples on their main page, but listed as an option in the API.
showSelectionCheckbox: true

Related

ng-Options is not refreshing the wired label when drop-down changed

Following Scott Allen's first code (simple) sample, after drop-down entry changes the wired ng-model is not refreshing this
{{engineer.currentActivity}}
Browser: FF 50.1.0
Angular: 1.5.9
jQuery: 1.7
HTML:
<div ng-controller="EngineeringController">
{{engineer.name}} is currently : {{engineer.currentActivity}}
<div>
choose an activity:
<select id="agDDLClient" ng-model="EngineeringController.currentActivity" ng-options ="act for act in activities">
</select>
</div>
<input type="button" ng-click="what()" value="check" />
</div>
JS:
var aIS = angular.module("app", []);
aIS.controller("EngineeringController", function($scope, $http)
{
$scope.engineer = {
name: "Dani",
currentActivity: "Fixing bugs"
};
$scope.activities =
[
"Writing code",
"Testing code",
"Fixing bugs",
"Dancing"
];
$scope.what = function(){ alert($scope.engineer.currentActivity);}
});
ng-model value should be engineer.currentActivity instead of EngineeringController.currentActivity as you are trying to alert the $scope.engineer.currentActivity inside what() function.
Working demo :
var myApp = angular.module('myApp',[]);
myApp.controller('EngineeringController',function($scope) {
$scope.engineer = {
name: "Dani",
currentActivity: "Fixing bugs"
};
$scope.activities = [
"Writing code",
"Testing code",
"Fixing bugs",
"Dancing"
];
$scope.what = function() {
alert($scope.engineer.currentActivity);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="EngineeringController">
{{engineer.name}} is currently : {{engineer.currentActivity}}
<div>
choose an activity:
<select id="agDDLClient" ng-model="engineer.currentActivity" ng-options ="act for act in activities">
</select>
</div>
<input type="button" ng-click="what()" value="check" />
</div>
Change to ng-model="engineer.currentActivity" instead of ng-model="EngineeringController.currentActivity"
and also your controller code should be follow this
var aIS = angular.module("app", []);
aIS.controller("EngineeringController", function($scope, $http)
{
$scope.engineer = {
name: "Dani",
currentActivity: "Fixing bugs"
$scope.activities =
[
"Writing code",
"Testing code",
"Fixing bugs",
"Dancing"
];
$scope.what = function(){ alert($scope.engineer.currentActivity);}
});

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>

angular material: md-select not working with "controller as" syntax?

All I did was modify their official Async Search demo (it fits my use case) to make use of "controller as", and getting weird behaviour as a result. Codepen is here. Am I missing anything?
Here's the relevant bits of code from the above link:
JS:
angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('SelectAsyncController', function($timeout, $scope) {
var vm = this;
vm.user = null;
vm.users = null;
vm.loadUsers = function() {
return $timeout(function() {
vm.users = vm.users || [
{ id: 1, name: 'Scooby Doo' },
{ id: 2, name: 'Shaggy Rodgers' },
{ id: 3, name: 'Fred Jones' }
];
}, 650);
};
});
Markup:
<div ng-controller="SelectAsyncController as vm" layout="column" ng-app="MyApp">
<md-select placeholder="Assign to user"
ng-model="vm.user"
md-on-open="vm.loadUsers()">
<md-option ng-value="vm.user"
ng-repeat="user in vm.users">{{user.name}}</md-option>
</md-select>
<p>Assigned to: {{ vm.user ? vm.user.name : 'No one yet' }}</p>
</div>
You should change ng-value to "user".
<md-option ng-value="user" ng-repeat="user in vm.users">{{user.name}}</md-option>
Here is the working Codepen.

How to copy selction into a new ui-grid

I am using Angular ui-grid (from ui-grid.info).
I have one ui-grid showing JSON Data delivered by a webapi-controller what works perfectly.
I added a second ui-grid with the same columsDef but no data.
I want to copy the (multi-)selected rows from grid1 to grid 2 using a button.
How would I access the selection to add it into the data of the second grid?
app.js
var app = angular.module('app', ['ui.grid', 'ui.grid.grouping','ui.grid.selection']);
app.controller('MainCtrl', ['$scope', '$http', '$log', 'i18nService', '$interval', 'uiGridGroupingConstants', function ($scope, $http, $log,i18NService, $interval, uiGridGroupingConstants) {
$scope.langs = i18NService.getAllLangs();
$scope.lang = 'de';
i18NService.setCurrentLang('de');
$scope.gridOptions = {
rowSelection:true,
enableFiltering: true,
enableRowSelection: true,
enableFullRowSelection :true,
enableSelectAll: true,
selectionRowHeaderWidth: 35,
rowHeight: 75,
showGridFooter:true,
treeRowHeaderAlwaysVisible: true,
columnDefs: [
{ name: 'Trigraph',field:'ZeigeTrigraphen',width:'10%'},
{ name: 'Titel', field: 'Titel', cellTemplate: '<td style="word-wrap:break-word;padding:5px;">{{ COL_FIELD }}</td>' },
{ name: 'Ziel', field: 'Ziel', cellTemplate: '<td style="word-wrap:break-word;padding:5px;">{{ COL_FIELD }}</td>' },
],
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
i18NService.setCurrentLang('de');
$http.get('/api/Alarmkalender/HoleAlle').then(function (resp) {
$scope.gridOptions.data = resp.data;
$log.info(resp);
});
html
<div class="container" ng-app="app">
#*<link rel="styleSheet" href="../../Scripts/ui-grid/ui-grid.min.css" />*#
<style>
.grid {
width: auto;
height: 350px;
}
</style>
<h2>Alarmmassnahmen</h2>
<div ng-controller="MainCtrl">
<div id="grid1" ui-grid="gridOptions" ui-grid-grouping class="grid"></div>
<button name="SpeichernButton" class="btn btn-success" id="btnSpeichern" type="submit" value="SpeichernButton"><i class="glyphicon glyphicon-save"></i> In Alarmkalender kopieren</button>
<div id="grid2" ui-grid="gridOptions2" class="grid"></div>
</div>
There are several ways to achieve your goal. I made a Plunker to demonstrate a possible solution.
You could create an ng-click on the row-template and gather all row selections. You either instantly load them into the new grid (as shown in Plunker) or load them all on external button-click.
There are basically three steps
First modify the row-Template
$templateCache.put('ui-grid/uiGridViewport',
...
"<div ng-repeat=\"(rowRenderIndex, row) in rowContainer.renderedRows track by $index\"" +
"ng-click=\"grid.appScope.addRowtoSelection(row)\"" +
...
);
Then you bind that addRowtoSelection() to your first grid and push selected rows into an array.
all.relectedRows = [];
all.gridOptions = {
...
appScopeProvider : {
addRowtoSelection : function(row) {
all.relectedRows.push(row.entity);
},
},
};
Finally you bind that array as new data to your second grid.
all.gridOptionsTwo = {
data: 'all.relectedRows',
...
};
e: If you want to use a button instead of instant addition of rows, you could use selectedRows as temporary array and reference selectedRowsData in your second grid. See updated Plunker.
HTML
<button ng-click="all.addRowsToSecondGrid();">Add Rows</button>
JavaScript
all.relectedRowsData = [];
all.addRowsToSecondGrid = addRowsToSecondGrid;
function addRowsToSecondGrid() {
all.relectedRowsData = [];
all.relectedRowsData = all.relectedRowsData.concat(all.relectedRows);
}
all.gridOptionsTwo = {
data: 'all.relectedRowsData',
...
Hopefully that helps.

ng-click inside cell template does not trigger function in controller

I have created a plunker here: http://plnkr.co/edit/zGqouwzxguef13lx48iP?p=preview
When I click in a cell of the ui-grid in the day view then nothing happens. What I expected is that the test function is executed and an alert is shown with text 'test' but that is not the case.
What is going on wrong here?
Thats the html cell template of the ui-grid 3.0 latest release:
HTML
<div ng-click="test()" ng-switch="row.entity[row.grid.columns.indexOf(col)].isPeriod">
<div ng-switch-when="true">
<tabset>
<tab>
<tab-heading>
<i class="glyphicon glyphicon-book"></i>
</tab-heading>period id:
{{ row.entity[row.grid.columns.indexOf(col)].id}}
</tab>
<tab select="alertMe()">
<tab-heading>
<i class="glyphicon glyphicon-bell"></i>
</tab-heading>
{{row.entity[row.grid.columns.indexOf(col)].content}}
</tab>
</tabset> <!-- PeriodTemplate -->
</div>
<div ng-switch-when="false">
<div>Hello empty template</div>
</div> <!-- EmptyPeriodTemplate -->
</div>
CONTROLLER:
'use strict';
angular.module('projectplanner').controller('DateplannerDayController', function ($scope, $state) {
var columnHeaderDates = ['col1','col2','col3','col4','col5','col6','col7']
$scope.columns = createColumnHeaders(columnHeaderDates);
var data = [{isPeriod: true, id: 10, rowNumber: 1},{isPeriod: false, id: 11, rowNumber: 2}]
$scope.test = function()
{
alert('test');
};
$scope.gridOptions = {
rowHeight: 200,
data: data,
enableSorting: false,
enableColumnMenu: false,
columnDefs: $scope.columns,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.core.addRowHeaderColumn(
{ name: 'rowHeaderCol',
displayName: '',
width: 100,
cellTemplate: '<div>row header template</div>'
});
}
};
function createColumnHeaders(columnHeaders) {
var columnDefinitions = [];
for (var i = 0; i < columnHeaders.length; i++) {
var column = {
name: columnHeaders[i],
cellTemplate: 'lessonplanner.day.celltemplate.html',
field: i + 'x'
}
columnDefinitions.push(column);
}
return columnDefinitions;
}
});
This page kept popping up in my searches and I managed to miss the solution in the comments. To summarize, you likely need to use externalScopes. See Angular ui-grid events in cell header not firing and http://ui-grid.info/docs/#/tutorial/305_appScope
If you are using Controller-As syntax then try:
ng-click= "grid.appScope.<controllerAliasName>.myFunction(row)"
It is because the ui-grid has its own controller and it doesn't know about the outside controller.
To facilitate, do the following..
1. First assign the controller to the ui-grid.
var vm = this;
this.$scope.usersGridOptions = {
appScopeProvider: vm,
....
}
Now, once you assign the controller to the grid, you can invoke the function like this..
"<a type=\"button\" href=\"\" ng-click=\"function(row.entity)\"> {{ row.entity.text}} </a>"
In ui-grid, cell-template, because of cell has its own scope,
1) do not use onclick='', instead should use ng-click=''
2) ng-click='your_function()' will not work, should use, grid.appScope.your_function()
3) when pass parameter in function(), do not use function({{xxx}}), see sample below
cellTemplate: '<div class="ui-grid-cell-contents" title="TOOLTIP">{{grid.appScope.editLink_tree_id(grid, row)}}</div>'

Resources