I'm close but still can't quite get this to work.
I have a new custom property editor that is loading correctly and is doing almost everything expected until I try to set the text field to be a jQuery UI element.
As soon as I add a directive in Angular for setting it to call the jQuery UI datepicker function, I get the following error suggesting it hasn't loaded the jQueryUI script library correctly:
TypeError: Object [object Object] has no method 'datepicker'
Trouble is, I can't see where I should be adding it as the logical places (to my mind, at least) seem to make no difference. Here is the code in full:
function MultipleDatePickerController($scope, assetsService) {
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
//assetsService
// .load([
// "http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"
// ])
// .then(function () {
// //this function will execute when all dependencies have loaded
// });
//load the seperat css for the editor to avoid it blocking our js loading
assetsService.loadCss("/css/jquery-ui.custom.min.css");
if (!$scope.model.value) {
$scope.model.value = [];
}
//add any fields that there isn't values for
//if ($scope.model.config.min > 0) {
if ($scope.model.value.length > 0) {
for (var i = 0; i < $scope.model.value.length; i++) {
if ((i + 1) > $scope.model.value.length) {
$scope.model.value.push({ value: "" });
}
}
}
$scope.add = function () {
//if ($scope.model.config.max <= 0 || $scope.model.value.length < $scope.model.config.max) {
if ($scope.model.value.length <= 52) {
$scope.model.value.push({ value: "" });
}
};
$scope.remove = function (index) {
var remainder = [];
for (var x = 0; x < $scope.model.value.length; x++) {
if (x !== index) {
remainder.push($scope.model.value[x]);
}
}
$scope.model.value = remainder;
};
}
var datePicker = angular.module("umbraco").controller("AcuIT.MultidateController", MultipleDatePickerController);
datePicker.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(function () {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(date);
});
}
});
});
}
}
});
I faced the same problem when adapting a jQuery Date Range Picker for my Date Range Picker package for Umbraco 7. It's frustrating! The problem (I think) is that Angular's ng-model listens for "input" changes to trigger events and so doesn't pick up on a jQuery triggered event.
The way around it I found was to force the input event of the element you wish to update to fire manually, using jQuery's .trigger() event.
For example, the date picker I was using had this code for when a date was changed:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
}
},
I just adapted it to force an input trigger by adding this.element.trigger('input') to the code block, so it now reads:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
this.element.trigger('input');
}
},
This forces Angular to "see" the change and then ng-model is updated. There may well be a more elegant way (as I'm an Angular newbie), but I know this worked for me.
Got it. This is probably a bit of a hack, but it's simple and effective so it's a win nonetheless.
The assetsService call is the key, where I've put code into the deferred .then statement to call jQueryUI's datepicker on any item that has the "jqdp" CSS class:
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
assetsService
.load([
"/App_Plugins/Multidate/jquery-ui.min.js"
])
.then(function () {
//this function will execute when all dependencies have loaded
$('.jqdp').datepicker({ dateFormat: 'dd/mm/yy' });
});
I've then gone and added that class to my view:
<input type="text" jqdatepicker name="item_{{$index}}" ng-model="item.value" class="jqdp" id="dp-{{model.alias}}-{{$index}}" />
Finally, I've added a directive to ensure that dynamically-added items also display a datepicker:
datePicker.directive('jqdatepicker', function () {
return function (scope, element, attrs) {
scope.$watch("jqdatepicker", function () {
try{
$(element).datepicker({ dateFormat: 'dd/mm/yy' });
}
catch(e)
{}
});
};
});
As I said, this is possibly a bit hacky but it achieves the right result and seems like a simple solution.
Related
I have a sortable list in React which is powered by jQuery UI. When I drag and drop an item in the list, I want to update the array so that the new order of the list is stored there. Then re-render the page with the updated array. i.e. this.setState({data: _todoList});
Currently, when you drag and drop an item, jQuery UI DnD works, but the position of the item in the UI does not change, even though the page re-renders with the updated array. i.e. in the UI, the item reverts to where it used to be in the list, even though the array that defines its placement has updated successfully.
If you drag and drop the item twice, then it moves to the correct position.
// Enable jQuery UI Sortable functionality
$(function() {
$('.bank-entries').sortable({
axis: "y",
containment: "parent",
tolerance: "pointer",
revert: 150,
start: function (event, ui) {
ui.item.indexAtStart = ui.item.index();
},
stop: function (event, ui) {
var data = {
indexStart: ui.item.indexAtStart,
indexStop: ui.item.index(),
accountType: "bank"
};
AppActions.sortIndexes(data);
},
});
});
// This is the array that holds the positions of the list items
var _todoItems = {bank: []};
var AppStore = assign({}, EventEmitter.prototype, {
getTodoItems: function() {
return _todoItems;
},
emitChange: function(change) {
this.emit(change);
},
addChangeListener: function(callback) {
this.on(AppConstants.CHANGE_EVENT, callback);
},
sortTodo: function(todo) {
// Dynamically choose which Account to target
targetClass = '.' + todo.accountType + '-entries';
// Define the account type
var accountType = todo.accountType;
// Loop through the list in the UI and update the arrayIndexes
// of items that have been dragged and dropped to a new location
// newIndex is 0-based, but arrayIndex isn't, hence the crazy math
$(targetClass).children('form').each(function(newIndex) {
var arrayIndex = Number($(this).attr('data-array-index'));
if (newIndex + 1 !== arrayIndex) {
// Update the arrayIndex of the element
_todoItems[accountType][arrayIndex-1].accountData.arrayIndex = newIndex + 1;
}
});
// Sort the array so that updated array items move to their correct positions
_todoItems[accountType].sort(function(a, b){
if (a.accountData.arrayIndex > b.accountData.arrayIndex) {
return 1;
}
if (a.accountData.arrayIndex < b.accountData.arrayIndex) {
return -1;
}
// a must be equal to b
return 0;
});
// Fire an event that re-renders the UI with the new array
AppStore.emitChange(AppConstants.CHANGE_EVENT);
},
}
function getAccounts() {
return { data: AppStore.getTodoItems() }
}
var Account = React.createClass({
getInitialState: function(){
return getAccounts();
},
componentWillMount: function(){
AppStore.addChangeListener(this._onChange);
// Fires action that triggers the initial load
AppActions.loadComponentData();
},
_onChange: function() {
console.log('change event fired');
this.setState(getAccounts());
},
render: function(){
return (
<div className="component-wrapper">
<Bank data={this.state.data} />
</div>
)
}
});
The trick is to call sortable('cancel') in the stop event of the Sortable, then let React update the DOM.
componentDidMount() {
this.domItems = jQuery(React.findDOMNode(this.refs["items"]))
this.domItems.sortable({
stop: (event, ui) => {
// get the array of new index (http://api.jqueryui.com/sortable/#method-toArray)
const reorderedIndexes = this.domItems.sortable('toArray', {attribute: 'data-sortable'})
// cancel the sort so the DOM is untouched
this.domItems.sortable('cancel')
// Update the store and let React update (here, using Flux)
Actions.updateItems(Immutable.List(reorderedIndexes.map( idx => this.state.items.get(Number(idx)))))
}
})
}
The reason jQuery UI Sortable doesn't work with React is because it directly mutates the DOM, which is a big no no in React.
To make it work, you would have to modify jQuery UI Sortable so that you keep the DnD functionality, but when you drop the element, it does not modify the DOM. Instead, it could fire an event which triggers a React render with the new position of the elements.
Since React uses a Virtual DOM, you have to use the function React.findDOMNode() to access an actual DOM element.
I would call the jQuery UI function inside the componentDidMount method of your component because your element has to be already rendered to be accessible.
// You have to add a ref attribute to the element with the '.bank-entries' class
$( React.findDOMNode( this.refs.bank_entries_ref ) ).sortable( /.../ );
Documentation - Working with the browser (everything you need to know is here)
Hope that makes sense and resolves your issue
i have created a directive to handle selectable provided by Jquery
mydirectives.directive('uiSelectable', function ($parse) {
return {
link: function (scope, element, attrs, ctrl) {
element.selectable({
stop: function (evt, ui) {
var collection = scope.$eval(attrs.docArray)
var selected = element.find('div.parent.ui-selected').map(function () {
var idx = $(this).index();
return { document: collection[idx] }
}).get();
scope.selectedItems = selected;
scope.$apply()
}
});
}
}
});
to use in html
<div class="margin-top-20px" ui-selectable doc-array="documents">
where documents is an array that get returned by server in ajax response.
its working fine i can select multiple items or single item
Issue: i want to clear selection on close button
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
i can write jquery in controller to remove .ui-selected class but its not recommended approach
can some one guide me whats the best practice to achieve these type of issue
Update:
i fixed the issue by broadcasting event on cancel and listening it on directive
$scope.clearSelection=function() {
$scope.selectedItems = [];
$timeout(function () {
$rootScope.$broadcast('clearselection', '');
}, 100);
}
and in directive
scope.$on('clearselection', function (event, document) {
element.find('.ui-selected').removeClass('ui-selected')
});
is this the right way of doing it or what is the best practice to solve the issue.
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
Datepicker using Jquery loses focus to the textbox after date selected. I am using jquery-ui-1.9.2.When a date is selected the focus not coming to the textbox.Any solution?
Try using the below code.
HTML code:
<input type="text" id="date"/>
JQuery:
$("#date").datepicker({
onClose: function () {
$(this).focus();
}
});
JSFiddle1
EDIT: The above code has a problem in IE, the datepicker is not getting closed. Here in this blog you can find the more information.
<script language='javascript' src="jquery-migrate-1.2.1.js"></script> // download and add this
$("#date").datepicker({
/* fix buggy IE focus functionality */
fixFocusIE: false,
onClose: function(dateText, inst) {
this.fixFocusIE = true;
this.focus();
},
beforeShow: function(input, inst) {
var result = $.browser.msie ? !this.fixFocusIE : true;
this.fixFocusIE = false;
return result;
}
});
JSFiddle2
$(".datepicker").datepicker({
onClose: function () {
$(this).parents().nextAll().find($(":input[type !='hidden']")).first().focus();
}
});
});
I have found an easier way that will put the focus on the next input, no matter how nested it is. You can always swap out the condition after the .find to whatever you like and it will bring the focus to that.
Initialise all the datepcikers on Doc Ready
$('.datepicker').datepicker(
{
onClose: function () {
this.focus();
}
});
Exapnding Praveen's answer.
I had one problem with it. On IE datepicker refused to show up each odd time I focused a field.
Also, there was a slight logical issue with that solution (which did not affect anything, but still not correct to my eye): fixFocusIE field is being set on options, but then later it is being called on "this", when "this" refers to DOM element and not options object. So essentially there are two fixFocusIE - one in options (unused) and the second one on DOM element itself.
And also $.browser.msie did not work anymore, I had to invent my own IE detector.
My working code looks like that:
var el = $("selector of element I need to assign to datepicker");
var options = {}; // actually I fill options from defaults and do some other manipulations, but I left it as empty object here for brevity
options.fixFocusIE = false;
function detectIE() {
var ua = window.navigator.userAgent;
if(ua.indexOf('MSIE ') > 0 ||
ua.indexOf('Trident/') > 0 ||
ua.indexOf('Edge/') > 0) {
return true;
}
// other browser
return false;
}
/* blur() and change() are needed to update Angular bindings, if any */
options.onSelect = function(dateText, inst) {
options.fixFocusIE = true;
$(this).blur().change().focus();
};
options.onClose = function(dateText, inst) {
options.fixFocusIE = true;
this.focus();
};
options.beforeShow = function(input, inst) {
var result = detectIE() ? !options.fixFocusIE : true;
options.fixFocusIE = false;
return result;
};
/* and this one will reset fixFocusIE to prevent datepicker from refusing to show when focusing the field for second time in IE */
el.blur(function(){
options.fixFocusIE = false;
});
el.datepicker(options);
Here is my case:
$('select').select2();
$('select').on('change', function () {
// calling a function
myFunction();
});
function myFunction() {
// changes my select values
// so I need to update the select for seing the news values
$('select').trigger('change');
// hehe I fire the change event so myFunction is called again and again
}
What can I do to avoid that behavior? Regards...
This is a bug in Select2. I had the same issue with the following code:
var FID = $(location).attr('href').split("/")[5];
$('#facility').children().each(function () {
if ($(this).val().trim() == FID.trim()) {
$(this).attr('selected', 'selected').trigger('change');
}
});
The following isn't ideal, but it does fix the issue. Note that you will need to redefine your Select2 options (mine shown).
var FID = $(location).attr('href').split("/")[5];
$('#facility').children().each(function () {
if ($(this).val().trim() == FID.trim()) {
$(this).attr('selected', 'selected');
$('#facility').select2({
placeholder: "",
minimumResultsForSearch: -1
});
}
});
In this JsFiddle : http://jsfiddle.net/maxl/mCXND/
(copied and modified from http://jsfiddle.net/ud3323/XMgwV/)
I try to create an Ember DatePicker based on JQuery's.
The first problem I run into is this line :
var ui = jQuery.ui[this.get('uiType')](options, this.get('element'));
jQuery.ui[this.get('uiType')] doesn't return a function, so I suppose that the solution
that I started with works for some jQueryUI widgets, but not all.
I would like a solution that will work for all JQuery-UI widgets,
and in particular JQueryUI's Datepicker.
Thanks
If you look at the jqueryui code, you see that some of them are invoked as a function, others not. You can solve it using this:
var ui;
if (typeof jQuery.ui[this.get('uiType')] === 'function') {
ui = jQuery.ui[this.get('uiType')](options, this.get('element'));
} else {
ui = this.$()[this.get('uiType')](options);
}
working example: http://jsfiddle.net/PzsrT/7/
One more thing about jQuery UI's datepicker widget as a EmberJS Mixin.
If you want to supply a callback function to handle the beforeShowDay event, you will raise this error:
Uncaught TypeError: Cannot read property '0' of undefined
even if your callback function (in your ember view) return an array, like it's specified in the jqueryui doc
beforeShowDay: function(date){
some code...
return [true, ''];
};
This happens because nothing is returned after the callback.call in the _gatherEvents function
_gatherEvents: function(options) {
var uiEvents = this.get('uiEvents') || [], self = this;
uiEvents.forEach(function(event) {
var callback = self[event];
if (callback) {
// You can register a handler for a jQuery UI event by passing
// it in along with the creation options. Update the options hash
// to include any event callbacks.
options[event] = function(event, ui) { callback.call(self, event, ui); };
}
});
}
I fix this by adding a return statement before the callback.call.
_gatherEvents: function(options) {
var uiEvents = this.get('uiEvents') || [], self = this;
uiEvents.forEach(function(event) {
var callback = self[event];
if (callback) {
// You can register a handler for a jQuery UI event by passing
// it in along with the creation options. Update the options hash
// to include any event callbacks.
options[event] = function(event, ui) { return callback.call(self, event, ui); };
}
});
}
working example http://jsfiddle.net/thibault/qf3Yu/