Tokens in TokenInput (Avoiding same pattern) - jquery-tokeninput

I want to know how to stop inputting same pattern value in TokenInput using Jquery ?
For Example : If i have something like "GM-123" and i dont want to have "GM-345" in the input field then what should i do ?
Anyone , please help.

I would make use of the onAdd callback, which is called when a token is added, and then remove the token if it shouldn't be allowed. Use something like this in your set up:
$(document).ready(function() {
$("#search_frwId").tokenInput(getMyRestServer, {
theme: "facebook",
queryParam: "param",
onAdd: function(hidden_input,item){
var newInput = item.name;
//Pattern Matching Magic Here
if(shouldNotBeAdded) $("#search_frwId").tokenInput("remove", item);
}
});
});
(This is untested code, I think passing the item back into remove like that will work, but am not 100% sure!)

Related

How to define a variable that's gonna be retrieved from localstorage (Chrome extension)?

I have a variable defined like this (not sure if it should be with let or var in the first place):
let activated = false;
The first thing that the extension should do is check the value of activated. I think this is the correct syntax:
chrome.storage.local.get(['activated'], function(result) {
activated = result.activated
alert ("activated: " + result.activated)
});
After some logic, I want to change activetedto true, with this syntax:
chrome.storage.local.set({activated: true}, function() {
console.log("activated changed to true: " + activated)
});
However, when I close and open the browser again, activatedis set to false again.
How should I structure this in order to achieve the desired result?
The way to acess a localstorage variable isn't by defining as I was doing in let activated = false;.
The way to add the variable retrieved from localstorage to the program's control flow should be done this way:
chrome.storage.local.get(['activated'], function(result) {
if (result.activated == value) { // Do something }
});

How do I format my AngularJS data model?

Hi I am just beginning with angular and I am struggling to find the answer to what I'm sure is quite a simple thing to do.
I am currently getting the values of some input boxes and pushing them into my scope. This is creating one long 'array' eg:
['data-1','data-2','data-3']
I would like to format my data in the following way instead
$scope.data = [
{
'header1': 'data1-1',
'header1': 'data1-2',
'header1': 'data1-3'
},
{
'header1': 'data2-1',
'header1': 'data2-2',
'header1': 'data2-3'
}
]
This is my function as it currently is.
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
$scope.td.push($(value).val());
});
}
Any help or pointers would be greatly appreciated as I am just getting my head round the angular way
Doing this isn't hard... but before I give you a gun to shoot yourself in the foot, just to say that I think it would be beneficial to explain WHY you want structure in that other format you are mentioning. You seem to have lots of data repetition and that's always a red flag.
Now for the code, you just need to create object before pushing it to the array like:
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
var obj = {
"header1": val + "-1",
"header2": val + "-2"
};
$scope.td.push(obj);
});
}
EDIT:
OK, so you are trying to add new row to the table. First of all, you shouldn't be doing angular.forEach, but rather those input elements in HTML should bind to existing scope object, like:
// obviously use better names than Input1Value
// I am here just giving you example
$scope.bindData = {
Input1Value: null,
Input2Value: null
};
// in HTML you will do
// <input ng-model="bindData.Input1Value" />
// <input ng-model="bindData.Input2Value" />
Now that you've eliminated that nasty angular.forEach you need to have some kind of event handler, for example when user clicks the button you want to add this object to the array to which table is data bound. Just be sure to clone the $scope.bindData object when you add it to array.
$scope.createRow = function(){
var newRowData = $scope.cloneObject($scope.bindData);
$scope.td.push(newRowData);
}
// http://heyjavascript.com/4-creative-ways-to-clone-objects/
// https://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
$scope.cloneObject = function(objToClone) {
var newObj = (JSON.parse(JSON.stringify(objToClone)));
}
To close this answer off - keep in mind, if you ever find yourself directly referencing HTML DOM elements in Javascript with AngularJS - you are doing something wrong. It's a nasty habit to eliminate, especially if you are coming from jQuery background (and how doesn't?), where everything is $("#OhHiThere_ElementWithThisId).
Obviously the main thread on this topic on StackOverflow is this one:
“Thinking in AngularJS” if I have a jQuery background?
However I find that it's too theoretical, so Google around and you may find better overviews like:
jQuery vs. AngularJS: A Comparison and Migration Walkthrough

Can't populate data with binding

This is my first try to make a single page application with HTML5. I'm using jquery, knockout and sammy.
Code: http://codepaste.net/apdrme
The problem is that I don't know what I'm doing wrong. I know it is the following:
this.get("#/", function() {
this.personList(this.persons);
});
But how else can I populate the list?
You could populate your list as follows:
function ViewModel() {
this.personList = ko.observableArray([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]);
};
[...]
ko.applyBindings(new ViewModel());
Pay attention to use ko.observableArray() at the declaration. So, you could also remove the argument and call this.personList([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]) in your main Sammy route and fill the list with other values in another route.
Another mistake is that you have used the with-binding that is not necessary here. Check the documentation about it.
You would normally use jQuery and an ajax call to populate personList. personList should be an ko.observableArray.
this.personList = ko.observableArray();
this.get("#/", function() {
$.ajax({url:"/api/persons/", dataType: 'json', success:function(persons){
this.personList(persons);
}});
});

Dynamically updated datalist won't show

I'm updating an html5 datalist dynamically, as the user types, with the following script:
$('#place').on('keyup', function() {
$.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() }).done(function(response) {
$('#autocomp-places').html(response);
});
});
Which works fine except that the datalist often doesn't show right away. When I inspect the element the html is there but the datalist is not shown as soon as it's updated. How can I force it to show?
For the record: it works... I just wish it would always show the new suggestion right away.
Please use success instead of done method of ajax and try again.
$('#place').on('keyup', function () {
$.post('content/php/autocomp.php', {
field: 'plaats',
val: $('#place').val()
}).success(function (response) {
$('#autocomp-places').html(response);
});
});
I think I just have found a decent workaround for this!
Here is my pseudo-code:
As I type, I make async httprequests to get data.
When data is returned, i clear and re-populate the datalist.
If the current input field is still focused, manually call .focus() on the input element (this seems to force the data-list popup behavior to occur).
First, I would try to use one of already available solutions such as the jQuery UI autocomplete. It will shorten your development time and make the code free of typical bugs (not to mention getting the benefits from someone else work in the future).
If you really want to create your own version, I would make sure the list is cleared and repopulated with the following code:
$('#place').on('keyup', function() {
var posting = $.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() });
posting.done(function(data) {
$('#autocomp-places').empty().append(data);
});
});

Using controller-scoped data in a directive's jqlite-generated html

This question is similiar to them one asked in Mike's post Using ng-model within a directive.
I am writing a page which is small spreadsheet that displays calculated output based on user input fields. Using a directive, I'm making custom tags like this:
<wbcalc item="var1" title="Variable 1" type="input"></wbcalc>
<wbcalc item="var2" title="Variable 2" type="input"></wbcalc>
<wbcalc item="calc" title="Calculation" type="calc"></wbcalc>
The 'item' field references scoped data in my controller:
$scope.var1 = '5'; // pre-entered input
$scope.var2 = '10'; // pre-entered input
$scope.calc = function() {
return parseInt($scope.var1) + parseInt($scope.var2);
};
And the 'type' field is used in the directive's logic to know whether to treat the item as a string or a function.
Here's a fiddle for this: http://jsfiddle.net/gregsandell/PTkms/3/ I can get the output elements to work with the astonishing line of code:
html.append(angular.element("<span>")
.html(scope.$eval(attrs.item + "()"))
);
...and I'm using this to get my inputs connected to my scoped controller data (I got this from Mike's post:
var input = angular.element("<input>").attr("ng-model", attrs.item);
$compile(input)(scope);
html.append(input);
...while it does put the values in the fields, they aren't bound to the calculation, as you can see by changing inputs in my fiddle.
Is there a better and/or more intuitive way to link my controller-scoped data to the jqlite-generated html in my directive?
Take a look at this, I think you can simplify the process a fair bit.
http://jsfiddle.net/PTkms/4/
angular.module('calculator', []).directive('wbcalc', function($compile) {
return {
restrict: 'E',
template: '<div><div class="span2">{{title}}</div><input ng-model="item"></div>',
scope: {
title: '#',
item: '='
},
link: function(scope, element, attrs) {
// Don't need to do this.
}
}
});
function calcCtrl($scope) {
$scope.var1 = '5';
$scope.var2 = '10';
$scope.calc = function() {
// Yes, this is a very simple calculation which could
// have been handled in the html with {{0 + var1 + var2}}.
// But in the real app the calculations will be more
// complicated formulae that don't belong in the html.
return parseInt($scope.var1) + parseInt($scope.var2);
};
}
I know you said you like jQuery - but to make best use of Angular you need to think in an Angular way - use bindings, don't manipulate the DOM directly etc.
For this example, it would be helpful to read up on the isolated scope bindings used - '#' and '=', see:
http://docs.angularjs.org/guide/directive