Issues formly with Angular Material modal - angularjs

I would like to show the forms in a modal using the Angle Material, but simply the controller is ignored.
Outside the modal, it operates normally, only the modal giving this problem ..
What did I doing wrong?
Any idea doque do?
angular.module('adminApp.forms', ['formly', 'formlyBootstrap', 'adminApp.services'], function config(formlyConfigProvider) {
formlyConfigProvider.setType({
name : 'repeatSection',
templateUrl : 'repeatSection.html',
controller : function($scope) {
$scope.formOptions = {formState: $scope.formState};
$scope.addNew = addNew;
$scope.copyFields = copyFields;
function copyFields(fields) {
return angular.copy(fields);
}
function addNew() {
$scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
var repeatsection = $scope.model[$scope.options.key];
var lastSection = repeatsection[repeatsection.length - 1];
var newsection = {};
// if (lastSection) {
// newsection = angular.copy(lastSection);
// }
repeatsection.push(newsection);
}
}
});
})
.controller('FormsController', function($scope, $mdDialog){
$scope.addField = function(ev){
$mdDialog.show({
parent : angular.element(document.body),
controller : FormsBuilder,
ariaLabel : 'Adicionar Campo',
targetEvent : ev,
clickOutsideToClose : true,
templateUrl : 'partials/tpl/fields.html',
})
function FormsBuilder($scope, FIELDS) {
console.log('start!')
var vm = this;
// funcation assignment
vm.onSubmit = onSubmit;
init();
//vm.originalFields = angular.copy(vm.fields);
// function definition
function onSubmit() {
console.log('submit!');
return
$scope.field = new FIELDS(vm.model);
$scope.field.$save(function(){
$scope.showToast('Field Group ....Criado!');
});
}
function init() {
console.log('init!')
vm.model = {
fields: []
};
vm.fields = [
{
"key": "fieldGroup-name",
"type": "input",
"templateOptions": {
"placeholder": "Nome do Grupo",
"label": "One add-on on the left (icon)"
}
},
{
type: 'repeatSection',
key: 'fields',
templateOptions: {
btnText:'Adicionar novo campo',
fields: [
{
className: 'row',
fieldGroup: [
{
className: 'col-xs-4',
type: 'input',
key: 'fieldName',
templateOptions: {
label: 'Nome do campo:'
}
},
{
type: 'input',
key: 'fieldSlug',
className: 'col-xs-4',
templateOptions: {
label: 'Slug do campo:'
}
}
]
},
{
"type": "select",
"key": "Fieldtype",
"templateOptions": {
"label": "Field Type",
"required": true,
"options": [
{
"name": "Text Field",
"value": "input"
},
{
"name": "TextArea Field",
"value": "textarea"
},
{
"name": "Radio Buttons",
"value": "radio"
},
{
"name": "Checkbox",
"value": "checkbox"
}
]
}
},
{
type: 'checkbox',
model: 'formState',
key: 'selfExecuting',
templateOptions: {
label: 'Are you executing this trade?'
}
},
{
hideExpression: '!formState.selfExecuting',
fieldGroup: [
{
type: 'input',
key: 'relationshipName',
templateOptions: {
label: 'Name:'
}
},
{
type: 'select',
key: 'complianceApprover',
templateOptions: {
label: 'Compliance Approver:',
options: [
{
name: 'approver 1',
value:'some one 1'
},
{
name: 'approver 2',
value:'some one 2'
}
]
}
},
{
type: 'textarea',
key: 'requestorComment',
templateOptions: {
label: 'Requestor Comment',
rows: 4
}
}
]
}
]
}
}
];
}
}
};
});
Modal template:
<md-dialog aria-label="Adicionar Campo">
<md-dialog-content>
<h1>Nome do Grupo: {{vm.exampleTitle}}</h1>
<form ng-submit="vm.onSubmit()" novalidate>
<formly-form model="vm.model" fields="vm.fields" form="vm.form">
<md-button type="submit" class="md-raised md-primary">Salvar</md-button>
</formly-form>
</form>
</md-dialog-content>
</md-dialog>
<script type="text/ng-template" id="repeatSection.html">
<div>
<div class="{{hideRepeat}}">
<div class="repeatsection" ng-repeat="element in model[options.key]" ng-init="fields = copyFields(to.fields)">
<formly-form fields="fields" model="element" bind-name="'formly_ng_repeat' + index + $parent.$index">
</formly-form>
<div style="margin-bottom:20px;">
<md-button type="submit" class="md-raised md-primary" ng-click="model[options.key].splice($index, 1)">Remover campo</md-button>
</div>
<hr>
</div>
<md-button type="button" class="md-raised md-primary" ng-click="addNew()" >{{to.btnText}}</md-button>
</div>
</script>
RESOLVED:
$mdDialog.show({
parent : angular.element(document.body),
controller : FormsBuilder,
controllerAs : 'vm',
ariaLabel : 'Adicionar Campo',
targetEvent : ev,
clickOutsideToClose : true,
templateUrl : 'partials/tpl/fields.html',
})

Related

Call Controller function from the directive in angular JS

I am using angular JS right now, in the i am using ui-bootstrap typeahead
I am trying scroll on demand logic in typeahead
i have tried this:
HTML:
<div class='container-fluid' ng-controller="TypeaheadCtrl">
<pre>Model: {{selected| json}}</pre>
<input type="text" ng-model="selected" maxlength="5" typeahead="country.name for country in countries | filter:$viewValue | limitTo:8">
</div>
JS:
angular.module('plunker', ['ui.bootstrap'])
.controller('TypeaheadCtrl', function ($scope) {
$scope.selected = undefined;
$scope.countries = [
{ name: "Afghanistan", code: "AF" },
{ name: "Aland Islands", code: "AX" },
{ name: "Albania", code: "AL" },
{ name: "Algeria", code: "DZ" },
{ name: "American Samoa", code: "AS" },
{ name: "Andorra", code: "AD" },
{ name: "Angola", code: "AO" },
{ name: "Anguilla", code: "AI" },
{ name: "Antarctica", code: "AQ" },
{ name: "Antigua and Barbuda", code: "AG" },
{ name: "Argentina", code: "AR" },
{ name: "Armenia", code: "AM" },
{ name: "Aruba", code: "AW" },
{ name: "Ascension Island", code: "AC" },
{ name: "Australia", code: "AU" },
{ name: "Austria", code: "AT" },
{ name: "Azerbaijan", code: "AZ" },
{ name: "Bahamas", code: "BS" },
{ name: "Bahrain", code: "BH" },
{ name: "Bangladesh", code: "BD" },
{ name: "Barbados", code: "BB" },
{ name: "Belarus", code: "BY" },
{ name: "Zimbabwe", code: "ZW" }
];
$scope.call= function(){
alert('reached end');
};
})
.directive('ul', function () {
return {
restrict: 'E',
link: function ($scope, element, attrs) {
element.bind('scroll', function (e) {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
// alert('end reached');
$scope.call();
}
})
}
}
});
But in the above try $scope.call(); function is not calling. Any one pls help me
REFERENCE PLUNKER
My actual requirement is when the scroll reaches the end, remaining records has to show in the typeahead
Make these changes to your directive, add a callBack scope variable in directive and add a callBack attribute in HTML , type function
.directive('ul', function () {
return {
restrict: 'E',
scope: {
callBack:"&"
}
link: function (scope, element, attrs) {
scope.callBack();
})
}
}
<div ul callBack="functionName"></div>

ng-click does not call function in mdDialog

I am a little new to AngularJS but I cannot figure out why the ng-click here will not call th addingSt() function, I wonder if it has something to do with the fact that it is being called from a mdDialog. Thanks for your help.
Heres my html for the mdDialog:
<md-dialog aria-label="Send Email">
<md-dialog-content>
<h3>Issue Details</h3>
<h4>Description</h4>
<md-input-container>
<label>Add description:</label>
<textarea class="form-control input-lg" style="width: 500px; height:100px;"></textarea>
</md-input-container>
<h3>Sub-tasks:</h3>
<md-list-item ng-repeat=" subtask in subtasks">
<p>{{subtask.content}}</p>
<md-checkbox aria-label="blarg" class="md-secondary" style="padding-right:60px;" ng-click="removeSubTask(subtask,$index)"></md-checkbox>
<md-list-item ng-if="addingTask === true"> <input ng-if="addingTask===true" ng-model="task.content" aria-label="blarg" placeholder="Add Subtask Here"></input>
</md-dialog-content>
<md-dialog-actions>
<md-button ng-show="addingTask === false" ng-click="addingSt()" class="btn btn-primary">
Add Sub-Task
</md-button>
<md-button ng-show="addingTask === true" ng-click="addingSt()" class="btn btn-primary">
cancel
</md-button>
<md-button ng-show="addingTask === true" ng-click="addSubTask()" class="btn btn-primary">
Submit
</md-button>
<md-button ng-click="closeDialog()" class="btn btn-primary">
Close
</md-button>
Here's the controller for the parent of the above mdDialog, (the controller for the mdDialog is nested inside it and works fine for all functions accept the addingSt() function)
var app = angular.module('epr')
app.controller('adminMainCtr',[ '$scope','$mdDialog',function($scope, $mdDialog) {
$scope.issues = [
{ name: 'Blizzard', img: 'img/100-0.jpeg', WardMessage: true, index:0, subtasks:[{content:"Shovel Sister Pensioner's Driveway "},
{content:"Clear downed trees at the Bush's home "}]},
{ name: 'Tornado', img: 'img/100-1.jpeg', WardMessage: false, index:1, subtasks:[{content:"",index:0}] },
{ name: 'Peterson Family Car Crash', img: 'img/100-2.jpeg', WardMessage: false, index:2, subtasks:[{content:"",index:0}] },
{ name: 'Flood', img: 'img/100-2.jpeg', WardMessage: false, index:3, subtasks:[{content:"",index:0}] },
{ name: 'School Shooting', img: 'img/100-2.jpeg', WardMessage: false, index:4, subtasks:[{content:"",index:0}] }
];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
//parent: parentEl,
templateUrl:'views/issue.html',
locals: {
items: $scope.items,
issue: issue
},
controller: DialogController
});
function DialogController($scope, $mdDialog) {
$scope.subtasks = issue.subtasks;
$scope.addingTask = false;
$scope.task={content:""};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask,index){
$scope.subtasks.splice(index,1);
}
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
Any help that you can lend me would be very appreciated!!!
You messed with the HTML and angylar code.
Errors found:
1) angular module initialization.
var app = angular.module('MyApp', ['ngMaterial'])
2) You placed some function outside the DialogController
3) md-list-item HTML has no end tags.
Created working Plunkr here. https://plnkr.co/edit/Sl1WzLMCd8sW34Agj6g0?p=preview . Hope it will solve your problem.
(function() {
'use strict';
var app = angular.module('MyApp', ['ngMaterial'])
app.controller('adminMainCtr', ['$scope', '$mdDialog', function($scope, $mdDialog) {
$scope.issues = [{
name: 'Blizzard',
img: 'img/100-0.jpeg',
WardMessage: true,
index: 0,
subtasks: [{
content: "Shovel Sister Pensioner's Driveway "
}, {
content: "Clear downed trees at the Bush's home "
}]
}, {
name: 'Tornado',
img: 'img/100-1.jpeg',
WardMessage: false,
index: 1,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Peterson Family Car Crash',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 2,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Flood',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 3,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'School Shooting',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 4,
subtasks: [{
content: "",
index: 0
}]
}];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
templateUrl: 'mddialog.html',
locals: {
message: {
items: $scope.items,
issue: issue
}
},
controller: DialogController
});
}
function DialogController($scope, $mdDialog, message) {
console.log(message)
//$scope.subtasks = message.issue.subtasks;
$scope.addingTask = false;
$scope.task = {
content: ""
};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask, index) {
$scope.subtasks.splice(index, 1);
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if ($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if ($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
})();

Kendo UI Scheduler with AngularJS - Update issue in custom edit template

We are using a custom editor template with custom fields in Agenda View. We have an edit button which fires the editEvent of scheduler. The problem is that, when we update the event, it doesn't fire the update operation.
As you can see, in "add new event" case, it works fine. Also while editing the "repetitive events with series" case, it fires the update operation as desired.
Only problem, we are having is that, while editing a single event (all day event or non-repetitive events), update operation is not fired.
Does anyone have any solution to this?
Here is the link to demo in telerik's dojo :
The HTML:
<div id="example" ng-app="KendoDemos">
<div ng-controller="MyCtrl">
<div class="thisTab clickhereTabScheduledcont boxWrapper">
<div class="agenda" style="position:relative;">
<div kendo-toolbar k-options="toolbarOptions" class="newEvent" id="toolbar" ng-click="schedulerOptions.addEvent()"></div>
<div kendo-scheduler="scheduler" k-options="schedulerOptions">
<span k-event-template class='custom-event'>
<span>{{dataItem.title}}</span>
<hr>
<i class="fa fa-pencil" ng-click="schedulerOptions.editEvent(dataItem)">Edit</i>
</span>
<div k-all-day-event-template class='custom-all-day-event'>{{dataItem.title}}</div>
</div>
</div>
</div>
</div>
Script section:
<script>
angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope){
$scope.toolbarOptions = {
items: [
{ type: "button", text: "New Event" }
]
};
$scope.schedulerOptions = {
date: new Date("2013/6/13"),
startTime: new Date("2013/6/13 07:00 AM"),
height: 600,
views: [
"agenda"
],
timezone: "Etc/UTC",
editable: {
template: kendo.template($("#customEditorTemplate").html())
},
dataSource: {
batch: true,
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/tasks",
dataType: "jsonp"
},
update: {
url: function (data) {
alert(JSON.stringify(data));
return "http://demos.telerik.com/kendo-ui/service/tasks/update";
},
dataType: "jsonp"
},
create: {
url: function (data) {
alert(JSON.stringify(data));
return "http://demos.telerik.com/kendo-ui/service/tasks/create";
},
},
destroy: {
url: "http://demos.telerik.com/kendo-ui/service/tasks/destroy",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
alert(operation);
}
},
schema: {
model: {
id: "taskId",
fields: {
taskId: { from: "TaskID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
description: { from: "Description" },
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
ownerId: { from: "OwnerID", defaultValue: 1 },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
},
filter: {
logic: "or",
filters: [
{ field: "ownerId", operator: "eq", value: 1 },
{ field: "ownerId", operator: "eq", value: 2 }
]
}
},
editEvent: function (dataItem) {
alert(JSON.stringify(dataItem));
$scope.scheduler.editEvent(dataItem);
},
addEvent: function () {
$scope.scheduler.addEvent({title: ""});
}
};
})
</script>
Ok,I think first we will pass scheduler event function in edit function.Then you can call api by eventId or as u like.
I have done this issue like that
This is your html template
<div class="thisTab clickhereTabScheduledcont boxWrapper">
<div class="agenda" style="position:relative;">
<div kendo-toolbar k-options="toolbarOptions" class="newEvent" id="toolbar" ng-click="schedulerOptions.addEvent()"></div>
<div kendo-scheduler="scheduler" k-options="schedulerOptions">
<span k-event-template class='custom-event'>
<span>{{dataItem.title}}</span>
<hr>
<i class="fa fa-pencil" ng-click="schedulerOptions.editEvent($event,$event.isRecurrenceHead())">Edit</i>
</span>
<div k-all-day-event-template class='custom-all-day-event'>{{dataItem.title}}</div>
</div>
</div>
</div>
Here is your controller
//you can pass scheduler default function in edit function
var editEventDetails ={};
update: {
url: function (data) {
console.log('update function');
var dt;
data.SignUpDueDate = moment(data.SignUpDueDate).format('YYYY-MM-DD') + "T23:59:59" + ".000Z";
data.ProgramTemplateId = editEventDetails.ProgramTemplateId;
data.IsTeamEvent = editEventDetails.IsTeamEvent;
data.SeasonTeamId = editEventDetails.SeasonTeamId;
data.Description = editEventDetails.Description;
data.CheckAttendance = editEventDetails.CheckAttendance;
data.Remarks = editEventDetails.Remarks;
data.IsSignUpRequired = editEventDetails.IsSignUpRequired;
API.post('/Scheduler/SaveProgramEvent', data).then(function (result) {
}
},
},
editEvent: function (evt) {
var uid = $(evt.target).closest('.k-task').attr("data-uid");
var event = $scope.scheduler.occurrenceByUid(uid);
event.startDate = moment(event.start).format('MM/DD/YYYY h:mm a');
event.endDate = moment(event.end).format('MM/DD/YYYY h:mm a');
dataItem.startDate = moment(event.start).format('MM/DD/YYYY h:mm a');
dataItem.endDate = moment(event.end).format('MM/DD/YYYY h:mm a');
$scope.scheduler.editEvent(event);
},
edit: function (e) {
console.log('EDIT');
if (e.event.eventMetaId != null && e.event.eventMetaId != undefined && e.event.eventMetaId != 0) {
var detailParams = {
EventMetaId: (e.event.recurrenceId !== 0 && e.event.eventMetaId === 0) ? e.event.recurrenceId : e.event.eventMetaId,
OwnerOrganizationId: _orgId,
UserTimezone: global.userTimezoneOffset// userTimezone
};
API.get('/Scheduler/GetEventDetailById', detailParams).then(function (data) {
editEventDetails = data;
mapEventDetail(editEventDetails, e.event)
});
setTimeout(function () {
e.event.startDate = moment(e.event.start).format('MM/DD/YYYY h:mm a');
e.event.endDate = moment(e.event.end).format('MM/DD/YYYY h:mm a');
e.event.recurrenceException = editEventDetails.recurrenceException;
$scope.$apply();
}, 0);
}
},
Here mapEventDetail is map function database and scheduler model
you can use mapEventDetail like that:--
var mapEventDetail = function (fromObj, toObj) {
toObj.programTemplateId = fromObj.ProgramTemplateId;
toObj.isTeamEvent = fromObj.IsTeamEvent;
toObj.seasonTeamId = fromObj.SeasonTeamId;
toObj.description = fromObj.Description;
toObj.checkAttendance = fromObj.CheckAttendance;
toObj.remarks = fromObj.Remarks;
return toObj;
};

Dynamically binding custom directive to ng-repeat

my controller has the json for my form then i have a directive that gets repeated to produce the form elements. based on the 'type' passed to the directive, the directive should know how to render the element.
but i don't know why it's not rendering the form templates properly here but that's a separate issue.
my immediate issue is, i can't seen to pass the ng-model and bind it correctly to the template.
does anyone see my problem?
var myApp = angular.module('myApp', []);
myApp.directive('ioProductElement', ['$compile', function ($compile) {
var dropdownTemplate = '<select ng-model="model" ng-options="option.Text for option in data"></select>';
var textAreaTemplate = '<textarea ng-model="model" class="form-control">{{ data }}</textarea>';
var radioListTemplate = '<span ng-repeat="item in data.Items"><input ng-model="model" type="radio" name="{{ data.Name }}" ng-checked="item.Selected" /><label>{{ item.ProductLabel }}</label> </span>';
return {
restrict: 'E',
replace: true,
scope: {
model: '=',
type: '=',
data: '='
},
link: function (scope, element) {
var getTemplate = function (type) {
var template = '';
switch (type) {
case 'SelectListItem':
template = dropdownTemplate;
scope.model = _.find(scope.data, {
Selected: true
});
break;
case 'TextArea':
template = textAreaTemplate;
break;
case 'RadioList':
template = radioListTemplate;
break;
}
return template;
};
element.html(getTemplate(scope.type));
$compile(element.contents())(scope);
}
};
}]);
myApp.controller('DynamicFormController', function () {
this.productElement = {};
this.product = {
ProductName: 'Online Form',
Company: 'TEST',
Data: []
};
this.productItems = [{
ProductLabel: "Status",
ProductType: "SelectListItem",
ProductData: [{
"Text": "Item1",
"Value": "1",
Selected: true
}, {
"Text": "Item2",
"Value": "2"
}]
}, {
ProductLabel: "Publication",
ProductType: "SelectListItem",
ProductData: [{
Text: 'Item1',
Value: '1'
}, {
Text: 'Item2',
Value: '2',
Selected: true
}]
}, {
ProductLabel: "Caption",
ProductType: "TextArea",
ProductData: "this is some data for the textarea"
}, {
ProductLabel: "Display Advertising",
ProductType: "RadioList",
ProductData: {
Name: "classifiedAdvertising",
Items: [{
Text: 'Full Page',
Selected: true
}, {
Text: '1/2 Page'
}]
}
}, {
ProductLabel: "Status2",
ProductType: "SelectListItem",
ProductData: [{
"Text": "Item1",
"Value": "1"
}, {
"Text": "Item2",
"Value": "2"
}, {
"Text": "Item3",
"Value": "3",
Selected: true
}]
}, ];
this.save = function () {
this.product.Data = this.productItems;
console.log('in save', this.product);
};
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.4.0/lodash.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div class="col-sm-12" ng-app="myApp">
<br />
<form class="form-horizontal" ng-controller="DynamicFormController as ctrl">
<div class="form-group" ng-repeat="item in ctrl.productItems">
<label class="col-sm-2 control-label">{{ item.ProductLabel }}</label>
<div class="col-sm-10">
<io-product-element data-model="ctrl.productElement[item.ProductLabel]" data-type="item.ProductType" data-data="item.ProductData"></io-product-element>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="button" class="btn btn-info" data-ng-click="ctrl.save()" value="Submit" />
product: {{ ctrl.product | json }}
</div>
</div>
</form>
</div>
Try To add a break statement in the first switch case
//[...]
switch (type) {
case 'SelectListItem':
template = dropdownTemplate;
scope.model = _.find(scope.data, {
Selected: true
});
break;
case 'TextArea':
template = textAreaTemplate;
break;
case 'RadioList':
template = radioListTemplate;
break;
}
//[...]

Creating a basic data grid with Kendo UI and AngularJS

I'm experimenting with AngularJS. I want to show a basic Kendo Grid. I'm trying to do this using pure directives. With that in mind, I've looked at the Kendo UI / Angular JS project (https://github.com/kendo-labs/angular-kendo). Unfortunately, my
index.html:
<div>Products: {{products.length}}</div>
<div kendo-grid k-data-source="products" k-selectable="'row'"
k-pageable='{ "refresh": true, "pageSizes": true }'
k-columns='[
{ "field": "Name", "title": "Name"},
{ "field": "Department", "title": "Department"},
{ "field": "LastShipment", "title": "Last Shipment" }
]'>
</div>
controllers.js
function myController($scope) {
console.log("initializing controller...");
$scope.products = [
{ id:1, name:'Tennis Balls', department:'Sports', lastShipment:'10/01/2013' },
{ id:2, name:'Basket Balls', department:'Sports', lastShipment:'10/02/2013' },
{ id:3, name:'Oil', department:'Auto', lastShipment:'10/01/2013' },
{ id:4, name:'Filters', department:'Auto', lastShipment:'10/01/2013' },
{ id:5, name:'Dresser', department:'Home Furnishings', lastShipment:'10/01/2013' }
];
}
I've verified that I've wired up the controller properly. The activity count shows properly. However, the grid does not appear. I can't figure out what I'm doing incorrectly.
Thank you for your help.
You can also setup a Kendo DataSource as an AngularJS Service using the Factory method and inject this into your Controller to conform to AngularJS best practices and patterns.
Full source code and live demo: http://goo.gl/6Z9jop
Customer.cshtml
#{
ViewBag.Title = "Index";
}
<div>
<h2 ng-cloak>{{title}}</h2>
<div>
<div class="demo-section">
<div class="k-content" style="width: 100%">
<div kendo-grid="grid"
k-sortable="true"
k-pageable="true"
k-filterable="true"
k-editable="'inline'"
k-selectable="true"
k-columns='[
{ field: "CustomerID", title: "ID", width: "75px" },
{ field: "CompanyName", title: "Company"},
{ field: "ContactName", title: "Contact" },
{ field: "ContactTitle", title: "Title" },
{ field: "Address" },
{ field: "City" },
{ field: "PostalCode" },
{ field: "Country" },
{ field: "Phone" },
{ field: "Fax" }]'
>
</div>
<style scoped>
.toolbar { padding: 15px; float: right; }
</style>
</div>
</div>
<script type="text/x-kendo-template" id="toolbar">
<div>
<div class="toolbar">
<button kendo-button ng-click="edit(this)"><span class="k-icon k-i-tick"></span>Edit</button>
<button kendo-button ng-click="destroy(this)"><span class="k-icon k-i-tick"></span>Delete</button>
<button kendo-button ng-click="details(this)"><span class="k-icon k-i-tick"></span>Edit Details</button>
</div>
<div class="toolbar" style="display:none">
<button kendo-button ng-click="save(this)"><span class="k-icon k-i-tick"></span>Save</button>
<button kendo-button ng-click="cancel(this)"><span class="k-icon k-i-tick"></span>Cancel</button>
</div>
</div>
</script>
</div>
</div>
customerController.js
'use strict';
northwindApp.controller('customerController',
function ($scope, $rootScope, $location, customerDataSource)
{
customerDataSource.filter({}); // reset filter on dataSource everytime view is loaded
var onClick = function (event, delegate)
{
var grid = event.grid;
var selectedRow = grid.select();
var dataItem = grid.dataItem(selectedRow);
if (selectedRow.length > 0)
{
delegate(grid, selectedRow, dataItem);
}
else
{
alert("Please select a row.");
}
};
$scope.toolbarTemplate = kendo.template($("#toolbar").html());
$scope.save = function (e)
{
onClick(e, function (grid)
{
grid.saveRow();
$(".toolbar").toggle();
});
};
$scope.cancel = function (e)
{
onClick(e, function (grid)
{
grid.cancelRow();
$(".toolbar").toggle();
});
},
$scope.details = function (e)
{
onClick(e, function (grid, row, dataItem)
{
$location.url('/customer/edit/' + dataItem.CustomerID);
});
},
$scope.edit = function (e)
{
onClick(e, function (grid, row)
{
grid.editRow(row);
$(".toolbar").toggle();
});
},
$scope.destroy = function (e)
{
onClick(e, function (grid, row, dataItem)
{
grid.dataSource.remove(dataItem);
grid.dataSource.sync();
});
},
$scope.onChange = function (e)
{
var grid = e.sender;
$rootScope.lastSelectedDataItem = grid.dataItem(grid.select());
},
$scope.dataSource = customerDataSource;
$scope.onDataBound = function (e)
{
// check if there was a row that was selected
if ($rootScope.lastSelectedDataItem == null)
{
return;
}
var view = this.dataSource.view(); // get all the rows
for (var i = 0; i < view.length; i++)
{
// iterate through rows
if (view[i].CustomerID == $rootScope.lastSelectedDataItem.CustomerID)
{
// find row with the lastSelectedProductd
var grid = e.sender; // get the grid
grid.select(grid.table.find("tr[data-uid='" + view[i].uid + "']")); // set the selected row
break;
}
}
};
});
customerDataSource.js
'use strict';
northwindApp.factory('customerDataSource',
function (customerModel)
{
var crudServiceBaseUrl = "/odata/Customer";
return new kendo.data.DataSource({
type: "odata",
transport: {
read: {
async: false,
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: function (data)
{
return crudServiceBaseUrl + "(" + data.CustomerID + ")";
},
type: "put",
dataType: "json"
},
destroy: {
url: function (data)
{
return crudServiceBaseUrl + "(" + data.CustomerID + ")";
},
dataType: "json"
}
},
batch: false,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: function (data) { return data.value; },
total: function (data) { return data["odata.count"]; },
model: customerModel
},
error: function (e)
{
alert(e.xhr.responseText);
}
});
});
It looks as if the field names are spelled wrong. The following works for me:
<div kendo-grid k-data-source="products" k-selectable="'row'"
k-pageable='{ "pageSize": 2, "refresh": true, "pageSizes": true }'
k-columns='[
{ "field": "name", "title": "Name"},
{ "field": "department", "title": "Department"},
{ "field": "lastShipment", "title": "Last Shipment" }
]'>
</div>
Here is a live demo: http://jsbin.com/odeQAfI/2/edit
To avoid the NaN message in the pager you need to make the products field to be a Kendo DataSource:
function MyController($scope) {
$scope.products = new kendo.data.DataSource({
data: [
{ id:1, name:'Tennis Balls', department:'Sports', lastShipment:'10/01/2013' },
{ id:2, name:'Basket Balls', department:'Sports', lastShipment:'10/02/2013' },
{ id:3, name:'Oil', department:'Auto', lastShipment:'10/01/2013' },
{ id:4, name:'Filters', department:'Auto', lastShipment:'10/01/2013' },
{ id:5, name:'Dresser', department:'Home Furnishings', lastShipment:'10/01/2013' }
],
pageSize: 2
});
}
Here is a live demo: http://jsbin.com/ODElUfO/2/edit

Resources