$scope issue on ngGridEventEndCellEdit event when i rollback data - angular-ui

I probably misunderstood something but here is my problem on plunker.
I put the relevant code here anyway:
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
var cellNameEditable =
'<cell-template model=COL_FIELD input=COL_FIELD entity=row.entity></cell-template>';
var cellNameDisplay =
'<div class="ngCellText" ng-class="col.colIndex()">{{row.getProperty(col.field)}}</div>';
$scope.myData= [{"id":1,"code":"1","name":"Ain"},{"id":2,"code":"2","name":"Aisne"},{"id":3,"code":"3","name":"Allier"},{"id":4,"code":"5","name":"Hautes-Alpes"},{"id":5,"code":"4","name":"Alpes-de-Haute-Provence"},{"id":6,"code":"6","name":"Alpes-Maritimes"},{"id":7,"code":"7","name":"Ardèche"},{"id":8,"code":"8","name":"Ardennes"},{"id":9,"code":"9","name":"Ariège"},{"id":10,"code":"10","name":"Aube"}];
$scope.gridOptions = {
data: 'myData',
multiSelect: false,
enableCellSelection: true,
enableRowSelection: false,
enableCellEditOnFocus: false,
rowHeight: 100,
columnDefs: [
{field:'id', displayName:'Id', visible: false},
{field:'code', displayName:'Code', enableCellEdit:true},
{
field:'name', displayName:'Name', enableCellEdit:true,
cellTemplate: cellNameDisplay,
editableCellTemplate: cellNameEditable
}
]
};
});
app.directive('cellTemplate', function () {
var cellTemplate =
'<div><form name="myForm" class="simple-form" novalidate>' +
'<input type="text" name="myField" ng-input="localInput" ng-model="localModel" entity="entity" required/>' +
'<span ng-show="myForm.myField.$error.required"> REQUIRED</span>' +
'localModel = {{localModel}} localInput = {{localInput}} entity = {{entity}}' +
'</form></div>';
return {
template: cellTemplate,
restrict: 'E',
scope: {
localModel:'=model',
localInput:'=input',
entity:'=entity'
},
controller: function ($scope) {
$scope.$on('ngGridEventStartCellEdit', function (event) {
console.log('cellTemplate controller - ngGridEventStartCellEdit fired');
$scope.oldEntity = angular.copy(event.currentScope.entity);
$scope.oldValue = angular.copy(event.currentScope.localModel);
});
$scope.$on('ngGridEventEndCellEdit', function(event) {
console.log('ngGridEventEndCellEdit fired');
if(event.currentScope.myForm.$valid) {
if(!angular.equals($scope.oldEntity, event.currentScope.entity)) {
alert('data saved !');
}
} else {
$scope.localModel = angular.copy($scope.oldValue);
$scope.localInput = angular.copy($scope.oldValue);
$scope.entity = angular.copy($scope.oldEntity);
}
});
}
};
});
Then explanations:
I have a ng-grid and based on the official example named "Excel-like Editing
Example" but with enableCellEditOnFocus option turned to false.
The cell "name" is defined in a directive containing a form to handle
data validation before updating the model.
I want to implement this behavior: When a user put invalid data, the
directive display error message and when the user leave the field, the
directive rollback data. If everything ok then I let the data updated.
The rollback part does not work. On the given plunker line 67 to 72 (last block on the code given here) it
fails to retore data. But my binding is with "=" so it should. Or maybe
because I am on the ngGridEventEndCellEdit event it breaks the links ?
I really don't understand why it fail.
So to reproduce my issue: enter in modification on a name cell, delete
all the data, REQUIRED is shown, then go out from the cell -> model is
not rolled back.

If you use a custom template, you should emit ngGridEventEndCellEdit event.

Related

ExtJS 6.01 How to update tpl after store loaded

Let's say I have a component with tpl in HTML format, which has a variable named testname, default value is null.
A listener of beforerender calls to a function in viewController, and in this function, I need to load a store and a callback function to update the variable testname in the view, based on the store record returned.
The problem I met is the order of code execution. The function in the viewController always ended first before the store.load callback get executed. Therefore the front view will never get updated. I have tried to setup the asynchronousLoad to false but it doesn't help.
Here is the code in the viewController.
onViewRendering: function(theView) {
console.log('setp 1');
var theStore = Ext.create('App.store.Test');
theStore.load({
asynchronousLoad: false,
callback: function(record) {
console.log('setp 2');
if (record) {
theView.data.testname = 'updated';
}
}
});
console.log('setp 3');
}
Console log displays in step 1, 3, 2.
And here is the code in the View:
Ext.define('App.view.TestView', {
extend: 'Ext.component',
data:{
testname:null
},
tpl:'<p>{testname}</p>',
listeners: {
beforerender: 'onViewRendering'
}
})
Here is the store code:
Ext.define('App.store.Test', {
extend: 'Ext.data.Store',
alias: 'store.test',
autoLoad: true,
remoteFilter: true,
fields: ['id', 'name'],
proxy: {
type: 'direct',
directFn: 'test.getTest'
}
})
I am new to Extjs and really need some help here, thanks in advance!
To update tpl after store load, you have to call setData method like below:
Code snippet:
onViewRendering: function(theView) {
console.log('setp 1');
var theStore = Ext.create('App.store.Test');
theStore.load({
asynchronousLoad: false,
callback: function(record) {
console.log('setp 2');
if (record) {
theView.setData({testname: 'updated'}); //setData method
}
}
});
console.log('setp 3');
}

Extend object on Meteor

When i add/edit blogPost, i've my object with all properties. My code :
Add post :
Template.postListAdmin.events({
'submit form': (e) => {
// Prevent default browser form submit
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted = false;
// If post draft, return true
if (draft.is(':checked')) isDrafted = true;
// If post image is small
// return true for add 'small' classe
if (image.height() < 80) isSmall = true;
let post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.insert', post);
setTimeout(() => {
$('#js-post-form')
.toggleClass('is-hidden')
.find('input, textarea').val('');
}, 500);
}
});
Edit post :
Template.postEdit.events({
'submit form': function (e) {
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted;
if (draft.is(':checked')) isDrafted = true;
else isDrafted = false;
if (image.height() < 80) isSmall = true;
let post = {
slug: $('[name="title"]').val(),
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
dateModified: new Date(),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.edit', this._id, post);
Router.go('postListAdmin');
},
});
I would like optimize my code and avoid creating my object 'post' 2x.
Do you have any idea how i can optim this ?
Thank you every boby :)
You should be able to achieve what you want to do by defining post without the let keyword.
For example:
post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
You will have to decide how you want to handle the two instances, though, since they are not exactly the same. Also, moving the variable definition outside of either file might be helpful for organizing your code. You could use a directory on the client named utils, and add a file that contains your global variable definitions.

How do I get translated column headers with Meteor and aldeed:tabular?

I'm running into the same problem as issue #53 of aldeed:tabular. When defining the table as suggested in the documentation, it is too soon to invoke a translation function (TAPi18n.__ or other), since the I18N variables are not yet set.
What is the nice, reactive way of feeding the translated column titles into DataTables, either directly as suggested by aldeed himself upon closing the issue, or through aldeed:tabular?
With .tabular.options
There is a way with the template's .tabular.options reactive
variable, but it is quirky. Here is a variation of the library
example using
tap-i18n to translate the
column headers:
function __(key) {
if (Meteor.isServer) {
return key;
} else {
return TAPi18n.__(key);
}
}
Books = new Meteor.Collection("Books");
TabularTables = {};
TabularTables.Books = new Tabular.Table({
name: "Books",
collection: Books,
columns: [] // Initially empty, reactively updated below
});
var getTranslatedColumns = function() {
return [
{data: "title", title: __("Title")},
{data: "author", title: __("Author")},
{data: "copies", title: __("Copies Available")},
{
data: "lastCheckedOut",
title: __("Last Checkout"),
render: function (val, type, doc) {
if (val instanceof Date) {
return moment(val).calendar();
} else {
return "Never";
}
}
},
{data: "summary", title: __("Summary")},
{
tmpl: Meteor.isClient && Template.bookCheckOutCell
}
];
}
if (Meteor.isClient) {
Template.tabular.onRendered(function() {
var self = this;
self.autorun(function() {
var options = _.clone(self.tabular.options.get());
options.columns = getTranslatedColumns();
self.tabular.options.set(_.clone(options));
});
});
}
With a forked version
I created a pull request against branch devel of meteor-tabular to enable the straightforward, reactive-based approach like so:
<template name="MyTemplateWithATable">
{{> tabular table=makeTable class="table table-editable table-striped table-bordered table-condensed"}}
</template>
var MyColumns = ["title", "author"];
// Assume translations are set up for "MyTable.column.title", "MyTable.column.author"
// in other source files; see TAPi18n documentation for how to do that
function makeTable() {
return new Tabular.Table({
name: "MyTable",
collection: MyCollection,
columns: _.map(MyColumns,
function(colSymbol) {
return {
data: colSymbol,
title: TAPi18n.__("MyTable.column." + colSymbol)
};
})
});
}
if (Meteor.isServer) {
// Called only once
makeTable();
} else if (Meteor.isClient) {
// Reactively called multiple times e.g. when switching languages
Template.MyTemplateWithATable.helpers({makeTable: makeTable});
}
Recent versions of aldeed:tabular allow to specify a function for setting the column titles.
import {TAPi18n} from 'meteor/tap:i18n';
TabularTables = {};
TabularTables.Departments= new Tabular.Table({
name: 'Departments',
collection: Departments,
responsive: true,
autoWidth: true,
stateSave: false,
columns: [
{data: "name", titleFn: function() {
return TAPi18n.__("name");
}},
{data: "description", titleFn: function() {
return TAPi18n.__("description");
}}
]
});
The language change is reactive. If you have translations you can switch and columns will be translated.
TAPi18n.setLanguage("en");
TAPi18n.setLanguage("de");
Word of warning:
This currently does not work when you include invisible columns in your table data. The offset is wrong and you get wrong column titles.

I'm doing model binding using backbone.stickit. How can I bind a prepopulated select with a model?

I have a form with a select populated with options. I want to bind it to a model using backbone.stickit but the documentation show how to populate the select on the binding configuration. I can't found an easy way to bind the model with my prepopulated select.
This is my html
<div id="main">
<form id="formulario">
<input id="test1" type="text" />
<select id="test2">
<option value="0">a</option>
<option value="1">b</option>
</select>
</form>
<div id="value-test1"></div>
<div id="value-test2"></div>
</div>
This is a working example based on the documentation, but not what I need
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
return [
{value: 0, label:'a'},
{value: 1, label:'b'}
];
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/nDjHh/
I tried to obtain the option values from the select on the binding configuration using jquery but doesn't work
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
options = $("#test2 option").map(function(){
return {value: this.value, label: this.text};
}).get();
return options;
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/2EYV7/2
It worked, but I think it will be a mess on forms with many selects
window.options = $("#test2 option").map(function(){
return {value: this.value, label: this.text};
}).get();
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
return window.options;
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/Y3aEF/1
What is the best way to bind a prepopulated select to a model?
I tried only with backbone.stickit, it's easier with another library?
Stickit actually binds values as data to select-options instead of using the value html attribute. The reasoning behind this is that in rich apps, you often want to use different types of data for option values. For example, you may want an option to represent a JavaScript Object or Array which is not an easy value to serialize to an html attribute; or you may want to assign the attribute value to the Number 2, but because of type coercion when it is saved as an attribue it will be converted to the String "2". Also, since Stickit is going to parse/own the select-options, it makes sense to let Stickit render the options instead of rendering/processing it in two places (not to mention iterating in a template is ugly).
That said, this request is common enough that I'm convinced to support pre-rendered select-options. Can you open a new issue, and I'll get something out on master within the next couple of days?
EDIT: This is being actively worked on, now.

Persisting json data in jstree through postback via asp:hiddenfield

I've been pouring over this for hours and I've yet to make much headway so I was hoping one of the wonderful denizens of SO could help me out. Here's the problem...
I'm implementing a tree via the jstree plugin for jQuery. I'm pulling the data with which I populate the tree programatically from our webapp via json dumped into an asp:HiddenField, basically like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(Items);
json = json.ToLower();
data.Value = json;
Then, the tree pulls the json from the hidden field to build itself. This works perfectly fine up until I try to persist data for which nodes are selected/opened. To simplify my problem I've hardcoded some json data into the tree and attempted to use the cookie plugin to persist the tree state data. This does not work for whatever reason. I've seen other issues where people need to load the plugins in a specific order, etc, this did not solve my issue. I tried the same setup with html_data and it works perfectly. With this working persistence I converted the cookie plugin to persist the data in a different asp:hiddenfield (we can't use cookies for this type of thing in our application.)
essentially the cookie operations are identical, it just saves the array of nodes as the value of a hidden field. This works with the html_data, still not with the json and I have yet to be able to put my finger on where it's failing.
This is the jQuery.cookie.js replacement:
jQuery.persist = function(name, value) {
if (typeof value != 'undefined') { // name and value given, set persist
if (value === null) {
value = '';
}
jQuery('#' + name).attr('value', value);
} else { // only name given, get value
var persistValue = null;
persistValue = jQuery('#' + name).attr('value');
return persistValue;
}
};
The jstree.cookie.js code is identical save for a few variable name changes.
And this is my tree:
$(function() {
$("#demo1").jstree({
"json_data": {
"data" : [
{
"data" : "A node",
"children" : [ "Child 1", "Child 2" ]
},
{
"attr": { "id": "li.node.id" },
"data" : {
"title": "li.node.id",
"attr": { "href": "#" }
},
"children": ["Child 1", "Child 2"]
}
]
},
"persistence": {
"save_opened": "<%= open.ClientID %>",
"save_selected": "<%= select.ClientID %>",
"auto_save": true
},
"plugins": ["themes", "ui", "persistence", "json_data"]
});
});
The data -is- being stored appropriately in the hiddenfields, the problem occurs on a postback, it does not reopen the nodes. Any help would be greatly appreciated.
After looking through this some more, I just wanted to explain that it appears to me that the issue is that the tree has not yet been built from the JSON_data when the persistence operations are being attempted. Is there any way to postpone these actions until after the tree is fully loaded?
If anyone is still attempting to perform the same type of operation on a jsTree version 3.0+ there is an easier way to accomplish the same type of functionality, without editing any of the jsTree's core JavaScript, and without relying on the "state" plugin (Version 1.0 - "Persistence"):
var jsTreeControl = $("#jsTreeControl");
//Can be a "asp:HiddenField"
var stateJSONControl = $("#stateJSONControl");
var url = "exampleURL";
jsTreeControl.jstree({
'core': {
"data": function (node, cb) {
var thisVar = this;
//On the initial load, if the "state" already exists in the hidden value
//then simply use that rather than make a AJAX call
if (stateJSONControl.val() !== "" && node.id === "#") {
cb.call(thisVar, { d: JSON.parse(stateJSONControl.val()) });
}
else {
$.ajax({
type: "POST",
url: url,
async: true,
success: function (json) {
cb.call(thisVar, json);
},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).responseText;
}
}
}
});
//If the user changes the jsTree, save the full JSON of the jsTree into the hidden value,
//this will then be restored on postback by the "data" function in the jsTree decleration
jsTreeControl.on("changed.jstree", function (e, data) {
if (typeof (data.node) != 'undefined') {
stateJSONControl.val(JSON.stringify(jsTreeControl.jstree(true).get_json()));
}
});
This code will create a jsTree and save it's "state" into a hidden value, then upon postback when the jsTree is recreated, it will use its old "state" restored from the "HiddenField" rather than make a new AJAX call and lose the expansions/selections that the user has made.
Got it working properly with JSON data. I had to edit the "reopen" and "reselect" functions inside jstree itself.
Here's the new functioning reopen function for anyone who needs it.
reopen: function(is_callback) {
var _this = this,
done = true,
current = [],
remaining = [];
if (!is_callback) { this.data.core.reopen = false; this.data.core.refreshing = true; }
if (this.data.core.to_open.length) {
$.each(this.data.core.to_open, function(i, val) {
val = val.replace(/^#/, "")
if (val == "#") { return true; }
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
else { remaining.push(val); }
});
if (current.length) {
this.data.core.to_open = remaining;
$.each(current, function(i, val) {
_this.open_node(val, function() { _this.reopen(true); }, true);
});
done = false;
}
}
if (done) {
// TODO: find a more elegant approach to syncronizing returning requests
if (this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
this.data.core.reopen = setTimeout(function() { _this.__callback({}, _this); }, 50);
this.data.core.refreshing = false;
}
},
The problem was that it was trying to find the element by a custom attribute. It was just pushing these strings into the array to search when it was expecting node objects. Using this line
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
instead of
if ($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
was all it took. Using a similar process I was able to persist the selected nodes this way as well.
Hope this is of help to someone.

Resources