dynamically get options of a dropdown menu in angular - html

The main problem is that I have a dropdown menu whose options should be updated dynamically.
The workflow is as follows:
I have an input element connected to an ng-model called toSubmit that when longer than 3 characters should fire an http.get call to fetch the list that should populate the dropdown menu.
So this list will change everytime the toSubmit variable changes. Let's call this list database (in the controller it is $scope.database.
What I am trying right now is a very simple solution that doesn't work most probably because the html DOM that contains the dropdown list is loaded at the very beginning and does not keep track of the changes in the options.
In my controller I have the following part which watches over toSubmit:
$scope.toSubmit = '';
$scope.$watch('toSubmit',function(query){
if (query.length >= 3){
getQueryDatabases.companyNameService({'field':'name','query':query,'numberOfHits':'10'},'CIK').prom.then(
function(dataObject){
$scope.database = dataObject;
// dataObject.forEach(function(item){
// $scope.databaseString.push(item.cik + ' ' + item.companyName);
});
});
}
});
And my html looks like the following:
<label for="nameCompany">Name:</label>
<input type="text" ng-model="toSubmit"></input>
<select ng-model="database" ng-options="line in database"></select>
Now my take was take by binding database with ng-Model I would get the result but I am most likely wrong. Can someone please help me?

I recommend you to use select2 that'll handle things like limiting input before server request and have great look and extendibility.
You need to add angular-ui-select2 to your project.
Here is code for you:
Html:
<input class='form-control' data-ng-model='position.company' data-ng-required data-placeholder='Company:' data-ui-select2='employerSelect2Options' id='company_name' type='hidden'>
JavaScript:
$scope.employerSelect2Options = {
minimumInputLength: 2,
query: function (query) {
var _query = query;
var companies = Restangular.all('companies').getList({query: query.term});
companies.then(function(data) {
var results = {results: []};
_.each(data, function(element, index, list) {
results.results.push({id: element.id, text: element.name});
})
if(!_.contains(_.map(data, function(element){ return element.name; }), _query.term)) {
results.results.push({id: _query.term , text: 'Create company "' + _query.term + '"'});
}
_query.callback(results);
})
}
};
My example also contains logic for add "create company" if zero results returned. In this case position.company will contain text of non found company name in id field and you can check it on server side and create one before assigning id.
This logic in
if(!_.contains
condition.

Related

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

angularjs save rendered values in html in a variable

I hope someone can help me with this, It's a strange question maybe as I didn't find an answer online.
I call the database and retrieve a list (in json) of items.
Then in angularjs,I render this list by extracting relevant pieces of data(name,age,etc) and show it properly in a table as a list of rows.
I have then an edit button that takes me to another page where I want to put a dropdown list.
What I want to know if is possible to add to that dropdown list the rendered list I previously created in my previous page.
is it possible to save the previously rendered list in a variable and then use that variable in the dropdown?
thank you
You could store the list within a controller and make this data availablte to this dropdown, I think.
Instead of trying to query for the list, add the list to the template, get the list from the template and render somewhere else, I'd suggest query for the list, save the list in a service , and then when you want to use that list again, get it from the service. Something like:
service:
var services = angular.module('services');
services.factory('getListService',['$http',function($http){
var getListOfStuff = function(){
//call to database
return //your json
};
var extractNameAgeEtc = function(){
var myListOfStuff = //get list of stuff from $http or database
var myListOfNameAgeEtc = //make a list of tuples or {name,age,etc} objects
return myListOfNameAgeEtc;
};
return {
extractNameAgeEtc : extractNameAgeEtc
};
}]);
controllers:
angular.module('controllers',['services']);
var controllersModule = angular.module('controllers');
controllersModule.controller('tableRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your table rendering template, probably with ng-repeat
$scope.MyTableValue = getListService.extractNameAgeEtc();
}]);
controllersModule.controller('dropdownRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your dropdown rendering template, probably with ng-repeat
$scope.MyDropDownValue = getListService.extractNameAgeEtc();
}]);

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

Getting Current Data from KendoUI TreeView

I'm using a kendo UI tree with a remote data source from a JSON file.
I have a button on the tree page which gets the current data of the tree,sends it through a POST to a server and the server saves the current data to the JSON file so as the next time I reload the page,the changes I made will be kept.That's what I want to happen.
So I know the current data of the tree is in:
$("#treeview").data("kendoTreeView").dataSource.data()
Which means the data changes real time in there for example when someone drag and drops a node of the tree.
My problem starts when this data doesn't seem to change when I drag and drop nodes inside the tree,and only changes when I drag and drop a node on the root level of the tree and even then it doesn't do it correcly as the node should be moved in there as well but instead the node gets copied,leaving the past node in the tree as well...
For Example I have this tree:
If I make a drag and drop change like this:
And I send the data,save it and reload the change isn't made at all!
PS:Even when I view the current data after the change before sending it,I see that there is no change on the data at all even though I did a change visualy with a drag and drop.So it doesn't have to do with the sending,saving and the server.
On the other hand,if I make a change like this:
I can see in the current data that the moved node is added in the end of the data indeed but it is not deleted from it's initial position within the data!So if i send the current data to the server,save it and then refresh I get the result:
The code for viewing and sending the data is:
function sendData() {
var req = createRequest();
var putUrl = "rest/hello/treeData";
req.open("post", putUrl, true);
req.setRequestHeader("Content-type","application/json");
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
alert(JSON.stringify(dsdata));
req.send(JSON.stringify(dsdata));
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
Is this a Bug or am I doing something wrong?Has anyone been able to see the current data changing correctly on every drag and drop?
First and most important you have to use the latest version of KendoUI (Kendo UI Beta v2012.3.1024) still in beta but is where they have solved many problems.
Then, when you create the kendoTreeView you have to say something like:
tree = $("#treeview").kendoTreeView({
dataSource :kendo.observableHierarchy(data),
dragAndDrop:true
}).data("kendoTreeView");
Here the important is not using directly data array but wrapping it with kendo.observableHierarchy.
Then you will have the data updated with the result of drag & drops.
For me in addition to OnaBai answer I had to use the sync function on the save method. I am using Type Script.
this.treeData = new kendo.data.HierarchicalDataSource({
data: kendo.observableHierarchy([]),//Thanks OnaBai
schema: {
model: {
id: "MenuItemId",
children: "MenuItemChildren",
hasChildren: (e) => {
//this removes arrow next to items that do not have children.
return e.MenuItemChildren && e.MenuItemChildren.length > 0;
}
}
}
});
public save() {
this.treeData.sync().done(() => {
console.log("sync data");
var myType = this.treeData.view();
this.$http.post("/api/TreeViewPicker", myType)
.then((response) => {
});
});
}

mvc3 entity framework - convert comma separated list of strings into list<string> in viewmodel, allow users to remove items from list

I am struggling to figure out how to do this with MVC,
I have an entity framework object that has a comma separated list from the db, (can't change the fact that its a horrible csl in the db). I can easily display the list and let them edit it manually. This is rather error prone and would like to split them up and display a list of them in the view. Then allow the user to click a link / button and have them removed from the string and db and the page refreshed to reflect this.
My first thought was to use JQuery to do a ajax json post to do a delete for each item the click an #Html.ActionLink for. I could get it to do the async post back and it would delete the item and would send back a string representing the new string list which I could update the UL with. The second time they clicked a link it would give me a 404, the script I used is:
<script type="text/javascript">
$(document).ready(function () {
$('.viewSeasonsLink').click(function () {
var data =
{
item: $(this).parents('li').first().find('.flagName').text(),
deploymentId: #Model.Id
};
$.post(this.href, data, function (result) {
var list = $("#testme");
list.empty();
var items = result.split(",");
$(items).each(function(index) {
// /* var link = '"' + #Html.ActionLink("Remove", "RemoveItemFromList", "Deployment", null, new { #class = "viewSeasonsLink" }) + '"'; */
var link = '<a class="viewSeasonsLink" href="/SAMSite/Deployment/RemoveItemFromList">Remove</a>';
list.append('<li><span class="flagName">' + items[index] + '</span> - ' + link + ' </li>');
/* list.append('<li><span class="flagName">' + items[index] + '</span> - ' + '\'' + #Html.ActionLink("Remove", "RemoveItemFromList", "Deployment", null, new { #class = "viewSeasonsLink" }) + '\'</li>'); */
});
}, "json");
return false;
});
});
</script>
I could not get the action link to work with the jquery script, so tried hard coding it, still not success.
I then thought I would just try and do a simple actionlink back to a method to remove it and return the normal view, again this posts and will update the db, but will not refresh the webpage at all.
<ul id="testme2">
#foreach (string flag in ViewBag.FeatureFlags)
{
<li><span class="flagName">#flag</span> - #Html.ActionLink("Remove", "RemoveItemFromListTest", "Deployment", null, new { #class = "viewSeasonsLink" })</li>
}
</ul>
public ActionResult RemoveItemFromListTest(string item, int deploymentId)
{
Deployment deployment = db.Deployments.Single(d => d.Id == deploymentId);
ViewBag.CustomerId = new SelectList(db.Customers, "Id", "Name", deployment.CustomerId);
List<string> featureFlags = deployment.FeatureFlags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
featureFlags.Remove(item);
deployment.FeatureFlags = ConvertBackToCommaList(featureFlags);
ViewBag.FeatureFlags = featureFlags;
//db.SaveChanges();
return View("Edit", deployment);
}
EDIT
released I was being a bit daft at one point:
The second test to get it to do a full post back and do the update was still getting caught by the jquery, (also was not passing in the values). I changed the line to this:
<li><span class="flagName">#flag</span> - #Html.ActionLink("Remove", "RemoveItemFromListTest", "Deployment", new { item = #flag, deploymentId = Model.Id }, null)</li>
which does work, but is a bit naff, it would mean any changes made to the form before the remove link clicked would be lost.
I think I see two issues. One is the initial .Post on the viewSeasonsList click event. You are posting back to the Action that loaded the page, not the Action that will handle the delete. I doesn't seem to me that they would be the same Action base on the approach you described.
var url = '/SAMSite/Deployment/RemoveItemFromList';
then
$.post(url, data, function (result) {
Second, in the Ajax response, when you are rebuilding the list, you are including an href attribute for the links. Why? you are not navigating with those links, you are initiating an Ajax request, which has already been set up.
var link = '<a class="viewSeasonsLink">Remove</a>';
ultimately I had one main problem with the jquery solution. When I added a new LI element it was not being hooked up to the ajax call as this was just happening at document.ready. I now replaced the simple .click with a delegate that will also hook up all elements that are added after the ready event, credit to this page for help with it:
$('#featureflaglist').delegate('.removeflaglink', 'click', RemoveFlagFromList);