Cannot pass Select2 parms into UI-select2 - angularjs-select2

I'm trying to use the ui-select2 Angular directive, and the github repo states:
All the select2 options can be passed through the directive. You can read more about the supported list of options and what they do on the Select2 Documentation Page
I have the directive working, but am unable to pass in simple options (ie: they are ignored).
For example:
html
<form>
<input type='hidden' ui-select2='selectGenes' ng-model='selectedGene' , ng-required="true">
</form>
js
$scope.selectGenes = {
minimumInputLength: 2,
'ajax': {
url: "/api/genes.json",
dataType: 'json',
data: function(term, page) {
return { q: term };
},
results: function(data, page) {
var index;
for (index = 0; index < data.length; ++index){
data[index].text = data[index].name2;
};
return { results: data };
}
}
};

I worked it out. The Select2 parms need to be quoted.
$scope.selectGenes = {
'minimumInputLength': 2,
'placeholder': 'Enter Gene',

Related

Uncaught TypeError: Cannot read property 'addEventListener' of null in .net on clear filter

I'm using Tabulator to implement search
Here's my html -- no problems until I try to search, then, I receive the above-captioned error:
<div>
<select id="filter-field">
<option></option>
<option value="custId">Customer ID</option>
<option value="custType">Customer Type</option>
<option value="custName">Customer Name</option>
<option value="groupId">Group ID</option>
</select>
<select id="filter-type">
<option value="=">=</option>
<option value="<"><</option>
<option value="<="><=</option>
<option value=">">></option>
<option value=">=">>=</option>
<option value="!=">!=</option>
<option value="like">like</option>
</select>
<input id="filter-value" type="text" placeholder="value to filter">
</div>
<div id="example-table"></div>
I'm receiving an error in the JavaScript:
````<script>
var table;
function handleCellUpdated(cell) {
console.log(cell);
console.log(cell.getRow());
console.log(cell.getRow().getData());
var record = cell.getRow().getData();
$.ajax({
url: "api/SalesTrackerCustomers/" + record.id,
data: JSON.stringify(record),
contentType: 'application/json',
type: "PUT",
success: function (response, textStatus, xhr) {
console.log("success")
},
error: function (XMLHttpRequest, textStatus, error) {
console.log("error")
}
});
}
function initTable() {
//Build Tabulator
table = new Tabulator("#customers", {
height: "90vh",
placeholder: "Loading...",
addRowPos: "bottom",
columns: [
{ title: "Customer ID", field: "custId", width: 150, editor: "input" },
{ title: "Customer Type", field: "custType", width: 130, editor: "input" },
{ title: "Customer Name", field: "customerName", editor: "input" },
{ title: "Group ID", field: "groupId", editor: "number" }
],
cellEdited: handleCellUpdated
});
loadCustomers();
}
function loadCustomers() {
console.log("loading data");
$.ajax({
url: "/api/SalesTrackerCustomers",
method: "GET"
}).done(function (result) {
table.setData(result);
});
}
// javascript for add/delete
//Add row on "Add Row" button click
document.getElementById("add-row").addEventListener("click", function () {
table.addRow({});
});
//Delete row on "Delete Row" button click
document.getElementById("del-row").addEventListener("click", function () {
table.deleteRow(1);
});
// javascript for search
//Define variables for input elements
var fieldEl = document.getElementById("filter-field");
var typeEl = document.getElementById("filter-type");
var valueEl = document.getElementById("filter-value");
//Custom filter example
function customFilter(data) {
return data.car && data.rating < 3;
}
//Trigger setFilter function with correct parameters
function updateFilter() {
var filterVal = fieldEl.options[fieldEl.selectedIndex].value;
var typeVal = typeEl.options[typeEl.selectedIndex].value;
var filter = filterVal == "function" ? customFilter : filterVal;
if (filterVal == "function") {
typeEl.disabled = true;
valueEl.disabled = true;
} else {
typeEl.disabled = false;
valueEl.disabled = false;
}
if (filterVal) {
table.setFilter(filter, typeVal, valueEl.value);
}
}
//Update filters on value change
document.getElementById("filter-field").addEventListener("change", updateFilter);
document.getElementById("filter-type").addEventListener("change", updateFilter);
document.getElementById("filter-value").addEventListener("keyup", updateFilter);
//Clear filters on "Clear Filters" button click
document.getElementById("filter-clear").addEventListener("click", function () {
fieldEl.value = "";
typeEl.value = "=";
valueEl.value = "";
table.clearFilter();
});
Can anyone add insight on this error? I have tried moving JavaScript around, and I think it may have to do with the placement of the JavaScript. It is displaying above captioned error on on //Clear filters on "Clear Filters" button click; it could also be on the load tabulator javascript function on table
The error you are receiving is because you are trying to add an eventListener to a null value. When using document.getElementById(''), if it does not find an element it returns null. Because you are not checking that you found an element, your .addEventListener tries to attach to a null value, so the error is thrown.
Looking at your code, there are three areas that do not have an html element (from what is included in the question)
There is not a filter-clear, add-row, or del-row element in your HTML. Based on you seeing the error above the document.getElementById('filter-clear').addEventListener(), it looks like your filter-clear element does not exist.
Here is an example that catches the error and appends the error to the body.
https://jsfiddle.net/nrayburn/58he2jr6/6/

Setting default values with selectize api for listbox in selectize.js

I am trying to set default value upon page load in a dropdown listbox which loads value thru an ajax call. Not able to set values using setValue method as suggested in the docs. Please help. Following are code snippets from the project
HTML
<select name="country" placeholder="Please Select Country ..."></select>
Data population JS code
$('[name="country"]').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
preload: true,
create: false,
render: {
option: function(item, escape) {
return '<div>' + escape(item['name']) + '</div>';
}
},
load: function(query, callback) {
$.ajax({
url: '/countrydata',
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
});
Default Value Setting Code
$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue("Japan");
Is there a hack where I can circumvent the problem ? I am been trying to get this work for couple of days now.
Thank you for reading. Any help would be appreciated.
You're close, but I believe your issue is that you're attempting to set the value to an option that doesn't exist in the list. You need to add the option first:
$('[name="country"]').selectize();
var item = {};
item.name = "Japan"; //Based on your render function, which uses item['name'] and labelField, searchField, etc.
$('[name="country"]')[0].selectize.addOption(item);
$('[name="country"]')[0].selectize.setValue(item.name);

Angularjs jQuery FIle Upload

I'm new at Angularjs and I'm trying to create an AngularJS project with jQuery File Upload but I could not distinguish between directives file controllers file and the view.
Can anyone help me by providing me a clear structure of how files should be placed? (controllers, directives, and view)
I wrote something for my very first Angular.js project. It's from before there was an Angular.js example, but if you want to see the hard way, you can have it. It's not the best, but it may be a good place for you to start. This is my directives.js file.
(function(angular){
'use strict';
var directives = angular.module('appName.directives', []);
directives.directive('imageUploader', [
function imageUploader() {
return {
restrict: 'A',
link : function(scope, elem, attr, ctrl) {
var $imgDiv = $('.uploaded-image')
, $elem
, $status = elem.next('.progress')
, $progressBar = $status.find('.bar')
, config = {
dataType : 'json',
start : function(e) {
$elem = $(e.target);
$elem.hide();
$status.removeClass('hide');
$progressBar.text('Uploading...');
},
done : function(e, data) {
var url = data.result.url;
$('<img />').attr('src', url).appendTo($imgDiv.removeClass('hide'));
scope.$apply(function() {
scope.pick.photo = url;
})
console.log(scope);
console.log($status);
$status.removeClass('progress-striped progress-warning active').addClass('progress-success');
$progressBar.text('Done');
},
progress : function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$progressBar.css('width', progress + '%');
if (progress === 100) {
$status.addClass('progress-warning');
$progressBar.text('Processing...');
}
},
error : function(resp, er, msg) {
$elem.show();
$status.removeClass('active progress-warning progress-striped').addClass('progress-danger');
$progressBar.css('width', '100%');
if (resp.status === 415) {
$progressBar.text(msg);
} else {
$progressBar.text('There was an error. Please try again.');
}
}
};
elem.fileupload(config);
}
}
}
]);
})(window.angular)
I didn't do anything special for the controller. The only part of the view that matters is this:
<div class="control-group" data-ng-class="{ 'error' : errors.image }">
<label class="control-label">Upload Picture</label>
<div class="controls">
<input type="file" name="files[]" data-url="/uploader" image-uploader>
<div class="progress progress-striped active hide">
<div class="bar"></div>
</div>
<div class="uploaded-image hide"></div>
</div>
</div>

select2 plugin works fine when not inside a jquery modal dialog

I am using select2 plugin inside a jquery dialog but in does not work. When dropping down, the focus moves to the input control but immediately get out from it,not allowing me to type anything.
This is the HTML:
<div id="asignar_servicio" title="Asignar servicios a usuarios">
<input type="hidden" class="bigdrop" id="a_per_id" />
</div>
And this is the javascript code:
$( "#asignar_servicio" ).dialog({
autoOpen: false,
height: 500,
width: 450,
modal: true,
buttons: {
"Cancelar": function () {
$('#asignar_servicio').dialog('close');
}
}
});
$("#a_per_id").select2({
placeholder: "Busque un funcionario",
width: 400,
minimumInputLength: 4,
ajax: {
url: "#Url.Action("Search", "Personal")",
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
};
},
results: function (data, page) {
return { results: data.results };
}
}
}).on("change", function (e) {
var texto = $('lista_personal_text').val().replace(/ /g, '');
if (texto != '')
texto += ',';
texto += e.added.text;
var ids = $('lista_personal_id').val().replace(/ /g, '');
if (ids != '')
ids += ',';
ids += e.added.id;
});
I have this same code in other page and it works.
Any help will be appreciated,
thanks
Jaime
jstuardo's link is good, but there's a lot to sift through on that page. Here's the code you need:
$.ui.dialog.prototype._allowInteraction = function(e) {
return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
};
Just add it next to wherever you are setting the select2 drop down.
An easy way:
$.ui.dialog.prototype._allowInteraction = function (e) {
return true;
};
add this after whereever you set select2
Or try this from:
Select2 doesn't work when embedded in a bootstrap modal
Remove tabindex="-1" from the modal div
I have found this workaround. https://github.com/ivaynberg/select2/issues/1246
Cheers
Jame
There's a new version of the fix for select2 4.0 from the github issue thread about this problem:
if ($.ui && $.ui.dialog && $.ui.dialog.prototype._allowInteraction) {
var ui_dialog_interaction = $.ui.dialog.prototype._allowInteraction;
$.ui.dialog.prototype._allowInteraction = function(e) {
if ($(e.target).closest('.select2-dropdown').length) return true;
return ui_dialog_interaction.apply(this, arguments);
};
}
Just run this before any modal dialogs that will have select2 in them are created.
JSFiddle of this fix in action
The best solution I found was just making the dialog not be a modal dialog by removing modal:true. Once you do this the page will function as desired.
After a while of battling with this I found another option that allows you to keep the dialog as a modal. If you modify the css for select2 to something like the following:
.select2-drop {
z-index: 1013;
}
.select2-results {
z-index: 999;
}
.select2-result {
z-index: 1010;
}
keep in mind that this works however if you open a lot of dialogs on the same page it will eventually exceed the z-index specified, however in my use case these numbers got the job done.
Not enough reputation to comment on a previous post, but I wanted to add this bit of code:
$('#dialogDiv').dialog({
title: "Create Dialog",
height: 410,
width: 530,
resizable: false,
draggable: false,
closeOnEscape: false,
//in order for select2 search to work "modal: true" cannot be present.
//modal: true,
position: "center",
open: function () { },
close: function () { $(this).dialog("distroy").remove(); }
});
$("#displaySelectTwo")select2();
Updating to the newer version of JQuery and Select2 is not an option in our application at this time. (using JQueryUI v1.8 and Select2 v1)
Add this after your select2() declaration.
$.ui.dialog.prototype._allowInteraction = function (e) {
return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-dropdown').length;
};
I've used the following fix with success:
$.fn.modal.Constructor.prototype.enforceFocus = function () {
var that = this;
$(document).on('focusin.modal', function (e) {
if ($(e.target).hasClass('select2-input')) {
return true;
}
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus();
}
});
}
I could fix this by removing the option: 'modal: true' from the dialog options.
It worked fine.
For anyone stumpling upon this with Select2 v4.0.12
I was using the Select2 option dropdownParent
i set the dropDownParent value, and still had the issue.
dropdownParent: $("#ReportFilterDialog")
What fixed it for me, was setting the value to, to select the outer layer of the modal dialog:
dropdownParent: $("#ReportFilterDialog").parent()

AngularJS : How to say to a directive to clone scope?

I have this fiddle, and can not make this work. I believe that the reason resides in that two li elements with a custom directive edit-in-place share scope.
The solution would be to say to the directive to create a copy of the scope that binds on the parent - can transclude help?
angular.module('bla', [])
.directive('editInPlace', ['$parse','$compile', function($parse, $compile) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attribs) {
var inputStart = '<input style="border: 2 solid black" name="inPlaceInput" style="display:none" value="';
var inputEnd = '">';
scope.editModeAccessor = $parse(attribs.editInPlace);
scope.modelAccessor = $parse(attribs.ngBind);
scope.$watch(attribs.editInPlace, function(newValue, oldValue){
if (newValue){
console.debug("click");
console.debug("value: " + scope.modelAccessor(scope));
var inputHtml = inputStart + scope.modelAccessor(scope) + inputEnd;
element.after(inputHtml);
jQuery(element).hide();
scope.inputElement = jQuery("input[name=inPlaceInput]");
scope.inputElement.show();
scope.inputElement.focus();
scope.inputElement.bind("blur", function() {
blur();
});
} else {
blur();
}
});
function blur(){
console.debug("blur secondary");
if (scope.inputElement){
console.debug("blur secondary inputElement found");
var value = scope.inputElement.val();
console.debug("input value: "+ value);
scope.inputElement.remove();
jQuery(element).show();
scope.editModeAccessor.assign(scope, false);
scope.modelAccessor.assign(scope, value);
}
}
}
}
}]);
function ContactsCtrl($scope, $timeout){
$scope.contacts = [{number:'+25480989333', name:'sharon'},{number:'+42079872232', name:''}];
$scope.editMode = false;
var editedId;
$scope.edit = function(id){
$scope.editMode = true;
jQuery("#"+id).hide();
editedId = id;
//TODO show delete button
}
$scope.$watch('editMode', function(newValue, oldValue){
if (!newValue && editedId){
jQuery("#"+editedId).show();
}
});
}
<div ng-app="bla">
<div ng-controller="ContactsCtrl">
<h4>Contacts</h4>
<ul>
<li ng-repeat="contact in contacts">
<span edit-in-place="editMode" ng-bind="contact.number"></span>
<span edit-in-place="editMode" ng-bind="contact.name"></span>
<span id="{{$index}}" ng-click="edit($index)"><i class="icon-edit">CLICKtoEDIT</i></span>
</li>
</ul>
</div></div>
I think cloning the scope is not the best solution.
When creating a directive in angular, you should encapsulate all the functionality within the directive. You should also avoid mixing jQuery in when you don't have to. Most of the time (as in this case) you're just introducing unnecessary complexity. Lastly, classes are the best way of controlling display, rather than the style attribute on an element.
I took the liberty of rewriting your directive in a more "angular" way - with no jQuery. As you can see from the updated jsFiddle, it is simpler and cleaner. Also, it works!
This directive can be easily modified to add lots of additional awesome functionality.
app.directive( 'editInPlace', function() {
return {
restrict: 'E',
scope: { value: '=' },
template: '<span ng-click="edit()" ng-bind="value"></span><input ng-model="value"></input>',
link: function ( $scope, element, attrs ) {
// Let's get a reference to the input element, as we'll want to reference it.
var inputElement = angular.element( element.children()[1] );
// This directive should have a set class so we can style it.
element.addClass( 'edit-in-place' );
// Initially, we're not editing.
$scope.editing = false;
// ng-click handler to activate edit-in-place
$scope.edit = function () {
$scope.editing = true;
// We control display through a class on the directive itself. See the CSS.
element.addClass( 'active' );
// And we must focus the element.
// `angular.element()` provides a chainable array, like jQuery so to access a native DOM function,
// we have to reference the first element in the array.
inputElement[0].focus();
};
// When we leave the input, we're done editing.
inputElement.prop( 'onblur', function() {
$scope.editing = false;
element.removeClass( 'active' );
});
}
};
});

Resources