Call ng-click function from ng-change function - javascript

I'm new in angularjs and please clear me if I'm wrong.
Im using single select and want to fetch the value and based on value I want to perform action. Eg: If I will get "DELETE" then I want to send it to ng-click function with name delete. Below is my code :-
html.jsp
<body ng-app ng-controller="AppCtrl">
<select ng-model="some_action.type" ng-change="actionchange(some_action.type)" ng-options="type.value as type.displayName for type in types">
</select>
</body>
script.js
function AppCtrl($scope) {
$scope.some_action={
type: 'Select'
}
$scope.types = [
{value: 'DELETE', displayName: 'Delete'},
{value: 'SUSPEND', displayName: 'Suspend'}
]
}
$scope.actionchange= function(value) {
console.log('change action is -'+ value);
//here I will fetch some ids which will sent to some other's click function
};
So i'm using ng-click function for both action seperately and want to be use from ng-change which will call ng-click.

function AppCtrl($scope) {
$scope.some_action = {
type: 'Select'
}
$scope.types = [{
value: 'DELETE',
displayName: 'Delete'
},
{
value: 'SUSPEND',
displayName: 'Suspend'
}
]
}
$scope.actionchange = function(value) {
console.log('change action is -' + value);
var fetchIds= [];
// based on the condition push all ids to fetchIDS
$scope.method_Delete(fetchIds);
};
$scope.method_Delete=function(fetchIds){
// do something using fetchIds
}

Related

knockout subscription not working

I have been trying to subscribe to when a dropdown value changes. I have the following logic however I cannot seem to get it working.
HTML
<div id="case-pin-#modelItem.CaseID" data-caseid="#modelItem.CaseID" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
JS
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function (newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
}
var pinObjs = [];
$(function () {
pinObjs = [];
$(".pinBinding").each(function () {
var caseId = this.getAttribute("data-caseid");
var view = new UserPinViewModel(caseId);
pinObjs.push(view);
ko.cleanNode(this);
ko.applyBindings(view, this);
});
})
The userPins array is populated by an AJAX call to the server as the values in the dropdown are dependent upon another section of the website which can change the values in the dropdown - here the logic I have used to populate the array.
function getPins() {
$.ajax({
type: 'POST',
url: '/Home/GetPins',
success: function (data) {
for (var i = 0; i < pinObjs.length; i++) {
pinObjs[i].userPins(data);
}
},
error: function (request, status, error) {
alert("Oooopppppsss! Something went wrong - " + error);
}
});
}
The actual values in the dropdowns all change to match what is returned from the server however whenever I manually change the dropdown, the subscription event is not fired.
You're using both jQuery and Knockout to manipulate the DOM, which is not a good idea. The whole idea of Knockout is that you don't manipulate the DOM, it does. You manipulate your viewModel.
Using cleanNode is also a code smell, indicating that you're doing things the wrong way. Knockout will handle that if you use the tools Knockout provides.
In this case, I was going to suggest a custom binding handler, but it looks like all you really want is to have a UserPinViewModel object created and applied to each instance of your .pinBinding element in the HTML. You can do that using the with binding, if you expose the UserPinViewModel constructor in your viewModel.
function UserPinViewModel(caseId) {
var self = this;
self.selectedPin = ko.observable();
self.userPins = ko.observableArray([]);
self.caseId = caseId;
self.selectedPin.subscribe(function(newValue) {
console.log(newValue);
//addCaseToPin(newValue, self.caseId);
});
// Pretend Ajax call to set pins
setTimeout(() => {
self.userPins([{
Name: 'option1',
Id: 1
}, {
Name: 'option2',
Id: 2
}, {
Name: 'option3',
Id: 3
}])
}, 800);
// Later, the options change
setTimeout(() => {
self.userPins([{
Name: 'animal1',
Id: 'Elephant'
}, {
Name: 'animal2',
Id: 'Pony'
}, {
Name: 'animal3',
Id: 'Donkey'
}])
}, 4000);
}
ko.bindingHandlers.pin = {
init: () => null,
update: () => null
};
ko.applyBindings({
pinVm: UserPinViewModel
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="case-pin-#modelItem.CaseID" data-bind="with: new pinVm('someCaseId')" class="row hidden popovercontainer pinBinding">
<select data-bind="options:userPins,
value:selectedPin,
optionsCaption:'-- please select --',
optionsText: 'Name',
optionsValue: 'Id'"></select>
</div>
Your getPins function suggests that the .pinBinding elements should correspond to the data being received. In that case, pinObjs should really be a part of your viewModel, and the elements should be generated (perhaps in a foreach) from the data, rather than being hard-coded. I don't know how that works with what I presume is the server-side #modelItem.CaseID, though.

how to call query call back data to data attribute select2

$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
maximumSelectionSize: 1,
placeholder: "Click here and start typing to search.",
data: function(query) {
queryData{!randomJsIden}(query);
},
matcher: function (term, text) {if (text.toUpperCase().indexOf(term.toUpperCase()) == 0){return true;}return false;}
});
function queryData{!randomJsIden}(query){
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.AutoCompleteV2_Con.getData}','{!sObjVal}','{!labelFieldVar}','{!valueFieldVar}',query.term,
function(result, event){
//if success
if(event.status){
var data = {results:[{ id: 1, text: "Ford" },
{ id: 2, text: "Dodge" },
{ id: 3, text: "Mercedes" },
{ id: 4, text: "Jaguar" }]}
query.callback( data);
}
},
{escape: true}
);
}
</script>
How to initialize query call back data to data attribute in select2 .
I cannot use data directly .In above example i am using sample data .
query : function(query){
queryData{!randomJsIden}(query);
}
I want to replace this by data attribute like this : the below one is not working
data : function(query){
queryData{!randomJsIden}(query);
}
here is the fiddle :
http://jsfiddle.net/Lnf8j/303/
Let me know any ideas from you
There are couple of issues in your code
you cannot name a function using flower braces as it is reserved notation symbol in javascript function queryData{!randomJsIden}(query), instead name it as function queryData(query){ ... }
if your adding a callback for data of your select2 then you need to return that data constructed from queryData() function.
data: function(query) {
return queryData(query);
},
function queryData(query){
...
return data;
}
If i'am not wrong,data is sourced to select2 via asynchronous call inside queryData(), which means the data is returned at unpredictable time,so you need to restrict the user from accessing the select2 component until data is feeded to it.
which means you either need to prefetch the data or disable the select2 field until data is returned from remote call.
Working Demo # JSFiddle

How to programatically add an option to an optiongroup in selectize.js

I want to dynamically add an option to an optiongroup in Selectize.js. The API only has
addOption(data)
updateOption(value, data)
addOptionGroup(id, data)
without much help on what "data" is. I've seen the examples for adding an option but no mention of using optionGroups
$('#button-addoption').on('click', function() {
control.addOption({
id: 4,
title: 'Something New',
url: 'http://google.com'
});
Thanks
Data is the object passed to the optgroup rendering method.
And so, you can put anything in it.
$('#selectize').selectize({
...
optgroupField: 'mygroup',
render: {
optgroup_header: function(data, escape) {
return '<div class="optgroup-header">' + escape(data.a) + escape(data.b) '</div>';
}
},
...
});
And then, whenever you want, you can add groups and options in the selectize:
//add group
var optGroup = { a: 'fruit', b: ... };
$('#selectize')[0].selectize.addOptionGroup('0', optGroup);
//add option
var option = { value: 'abc', text: 'banana', mygroup: '1'};
$('#selectize')[0].selectize.addOption(option);
Of course, if you only want a label for the group, you can do this:
//code
...
render: {
optgroup_header: function(data, escape) {
return '<div class="optgroup-header">' + escape(data) + '</div>';
}
...
//code
$('#selectize')[0].selectize.addOptionGroup('1', 'meat');
You can see the API demo (search for 'Optgroups (programmatic)' in page).

Adding additonal Selected value in Select2 on button click?

The scenario is, I need to append a value (a selected Value) to select2 by just clicking a button. What happen is if I click my button, the other values I selected are gone/cleared.
Only 1 value is selected which is the value in my button function. I could select multiple values when typing directly to my select2 textbox, but then if i clicked the button, its value doesn't add to select2.
How do i append a value or push an additional value to data already selected in select2 on my click Button? a new value should be added to select2 selected values everytime I click the button.
I hope my code below, and my description to what im looking for kinda help you guys. Thank you.
I'm using Northwind DataBase, for testing it. (Robert King is under Employee Table)
<input type="button" onclick="Passvalue();"/>
<input type="text" id="eq" name="eq" style="width: 200px;" />
<script>
$(function () {
$("#eq").select2({
minimumInputLength: 3,
multiple: true,
ajax: {
url: '/Employee/GetAllEmployees/',
dataType: 'json',
type: "GET",
data: function (searhTerm) {
return { query: searhTerm };
},
results:
function (data) {
return { results: data};
},
},
initSelection: function (element, callback) {
var id=$(element).val(); //element value will be 'Robert';
if (id!=="") {
$.ajax('/Employee/GetAllEmployees/', {
data: {
query: id
},
dataType: "json",
type: "GET",
}).done(function(data) { callback(data); });
}
},
createSearchChoice: function (term) {
return {id: term, text: term + ' (new)', title: term };
},
formatResult: FormatContact,
formatSelection: FormatContactSelection,
escapeMarkup: function(m) {
return m;
}
});
});
function FormatContact(contact) {
return contact.text + " (" + contact.title + ")";
}
function FormatContactSelection(contact) {
return " "+ contact.text;
}
function Passvalue() {
var test2 = "Robert"; //just an example, value 'Robert' to be passed on select2 for query
$('#eq').select2("val", [test2]);
}
</script>
My Action Controller:
public ActionResult GetAllEmployees(string query)
{
var db = new Employee().GetAllEmployees(query).
ToList();
return Json(db, JsonRequestBehavior.AllowGet);
}
BL:
public IQueryable<Object> GetAllEmployees(string search)
{
var ctx = new NorthwindEntities();
var dbQuery =
(from i in ctx.Employees
where i.FirstName.Contains(search) || i.LastName.Contains(search)
select new
{
id = i.EmployeeID,
text = i.FirstName + " " + i.LastName,
title = i.Title
});
return dbQuery;
}
Instead of using "val" use "data". Something like this
this.$("#yourSelector").select2("data", [{ id: 1, text: "Some Text" },{ id: 2, text: "Some Other Text" }]);
So something like this would work for you...
var existingData = this.$("#yourSelector").select2("data");
existingData.push({ id: 11, text: "Some Text" });
this.$("#yourSelector").select2("data", existingData);
P.S : I have not tested the above code.

get selectItem on change event

Given the following code in Sencha Touch (pr3), I allways get "all" in the alert.
{
xtype:'selectfield',
options: [
{text: 'AllInboxes(5)', name:'all',value: 'all'},
{text: 'Correspondence(2)',name:'cores', value: 'correspondence'},
{text: 'ERP(2)', name:'erp',value: 'erp'},
{text: 'Media(1)', name:'med', value: 'media'}
],
listeners: {
change: function(value){
alert(value.originalValue);
//Pass value parameter to the 2nd select field's store
}
},
}
Could some one please let me know what is the issue ?
Below code works:
change: function(field, value) {
if (value instanceof Ext.data.Model) {
value = value.get(field.getValueField());
}
console.log(value);
//Pass value parameter to the 2nd select field's store
}
See the documentation for the change listener.
It take three parameters
field
new value
old value
So try to use it this way :
change: function(field, newValue, oldValue){
alert(newValue);
}
Hope this helps

Categories