Generate dynamic drop down with options from an Angular controller - javascript

In my view file I've one button. I want to append drop down on click of button.
Here is my code:
Controller File
$scope.appendnewrow = function (result) {
var tr = '<select><option ng-repeat="'+site in
result+'">'+site.name+'</option></select>';
var temp = $compile(tr)($scope);
angular.element(document.getElementById('123')).append(temp);
}
View File
<a ng-click="appendnewrow(result)">Add domain</a>
When I ran this code options did not populate.

This is not the Angular way do to that.
Considering your data is in $scope.result, you can display the array using ng-options:
<a ng-click="addRow(row)">Add domain</a>
<select ng-options="site as site.name for site in result"></select>
Add this function in your controller:
$scope.addRow = function(newRow) {
$scope.result.push(newRow);
}
Here is a JSFiddle demo of what it could looks like.

Related

AngularJS - Get printed value from scope inside an attribute?

I'm currently working on an AngularJS project and I got stuck in this specific requirement.
We have a service that has all the data, DataFactoryService. Then, I have a controller called DataFactoryController that is making the magic and then plot it in the view.
<div ng-repeat = "list in collection">
{{list.name}}
...
</div>
Now, we have a requirement that pass multiple data into one element. I thought an "ng-repeat" would do, but we need to have it inside an element attribute.
The scenarios are:
At one of the pages, we have multiple lists with multiple data.
Each data has a unique code or ID that should be passed when we do an execution or button click.
There are instances that we're passing multiple data.
Something like this (if we have 3 items in a list or lists, so we're passing the 3 item codes of the list):
<a href = "#" class = "btn btn-primary" data-factory = "code1;code2;code3;">
Submit
</a>
<a href = "#" class = "btn btn-default" data-factory = "code1;code2;code3;">
Cancel
</a>
In the example above, code1,code2,code3 came from the list data. I tried several approach like "ng-repeat", "angular.each", array, "ng-model" but I got no success.
From all I've tried, I knew that "ng-model" is the most possible way to resolve my problem but I didn't know where to start. the code below didn't work though.
<span ng-model = "dataFactorySet.code">{{list.code}}</span>
{{dataFactorySet.code}}
The data is coming from the service, then being called in the controller, and being plot on the HTML page.
// Controller
$scope.list = dataFactoryService.getAllServices();
The data on the list are being loaded upon initialization and hoping to have the data tags initialized as well together with the list data.
The unique code(s) is/are part of the $scope.list.
// Sample JSON structure
[
{ // list level
name: 'My Docs',
debug: false,
contents: [ // list contents level
{
code: 'AHDV3128',
text: 'Directory of documents',
...
},
{
code: 'AHDV3155',
text: 'Directory of pictures',
...
},
],
....
},
{ // list level
name: 'My Features',
debug: false,
contents: [ // list contents level
{
code: 'AHGE5161',
text: 'Directory of documents',
...
},
{
code: 'AHGE1727',
text: 'Directory of pictures',
...
},
],
....
}
]
How can I do this?
PLUNKER -> http://plnkr.co/edit/Hb6bNi7hHbcFa9RtoaMU?p=preview
The solution for this particular problem could be writing 2 functions which will return the baseId and code with respect to the list in loop.
I would suggest to do it like below
Submit
Cancel
//inside your controller write the methods -
$scope.getDataFactory = function(list){
var factory = list.map( (a) => a.code );
factory = factory.join(";");
return factory;
}
$scope.getDataBase= function(list){
var base= list.map( (a) => a.baseId);
base= base.join(";");
return base;
}
Let me know if you see any issue in doing this. This will definitely solve your problem.
You don't really have to pass multiple data from UI if you are using Angular.
Two-way data binding is like blessing which is provided by Angular.
check your updated plunker here [http://plnkr.co/edit/mTzAIiMmiVzQfSkHGgoU?p=preview]1
What I have done here :
I assumed that there must be some unique id (I added Id in the list) in the list.
Pass that Id on click (ng-click) of Submit button.
You already have list in your controller and got the Id which item has been clicked, so you can easily fetch all the data of that Id from the list.
Hope this will help you... cheers.
So basing from Ashvin777's post. I came up with this solution in the Controller.
$scope.getFactoryData = function(list) {
var listData = list.contents;
listData = listData.map(function(i,j) {
return i.code;
});
return listData.join(';');
}

PHP-CodeIgniter: How to get the corresponding html table row values to be deleted by Javascript

In my codeigniter project i'm using a Table in which it is dynamically generated by Ajax. on the each row there is a button to Delete the corresponding row from Html Table and Mysql table too.
i tried it already. and i get the code to remove Html table row , and it follows
$(document).on('click', '#deleteRow', function() {
$(this).parent().parent().remove();
});
and it worked. but i want to delete that corresponding row from Mysql too. so first of all , it needs to be pass the corresponding row informations from javascript. then pass this to the Controller via URL.?
window.location.href = "<?php echo base_url("settings/remove_company"); ?>?id="+current;
How i get corresponding row informations such as company_id, lic_id (field names of html table).?
any help would be greatly appreciated .
Add attributes to the <tr>
<tr data-companyId="<?php echo $companyId;?>" data-licId="<?php echo $licId;?>">
In your jQuery, get those attributes on click of delete link:
$(document).on('click', '#deleteRow', function() {
var companyId = $(this).parent().parent().attr('data-companyId');
var licId = $(this).parent().parent().attr('data-licId');
$(this).parent().parent().remove();
});
Even, you can do object caching (using variable instead of object to improve performance.
$(document).on('click', '#deleteRow', function() {
var obj = $(this).parent().parent();
var companyId = obj.attr('data-companyId');
var licId = obj.attr('data-licId');
obj.remove();
});

Angularjs: HTML DOM is not updated

I've an inherited project writed in django 1.4 and I've no time to update it to another version of django.
I'm introducing angularjs in that project being newbie with it.
So, I've a HTML filled with data from the database (very simplified code):
<div ng-app="myApp" ng-controller="commentController">
<input placeholder="say something!" type="text">
<button class="btn" ng-click="sendComment()" >
<li ng-repeat="comment in comments" id="aportacion{{comment.pk}}">
{{comment.username}} - {{comment.text}}
</li>
</div>
And angularjs app (simplified) to fill the table with comments:
var app = angular.module("myApp", []);
app.controller("commentController",function ($scope) {
$scope.comments = [];
// this is generated dinamically with django from db data on page generation;
$scope.comments[$scope.comments.length] = {"username":"inigod", "text":"this is sparta"};
$scope.comments[$scope.comments.length] = {"username":"another guy", "text":"this is NOT sparta"};
.......
};
});
This works great, it builds all the comments ok, nice.
Now I've a textbox to add new comment and want to send via ajax the new comment to db and with the response json add a new comment in the top of the comments in html.
I've tried modificating the angularjs code to this:
app.controller("commentController",function ($scope) {
$scope.comments = [];
// this is generated dinamically with django from db data on page generation;
$scope.comments[$scope.comments] = {"username":"inigod", "text":"this is sparta"};
$scope.comments[$scope.comments] = {"username":"another guy", "text":"this is NOT sparta"};
$scope.sendComment = function(){
Dajaxice.kolokvoweb.post_comment($scope.comment_callback, {'thread':'{{thread.pk}}',
'type': 0,
'text': $('#comment').val(),
});
}
$scope.comment_callback = function (data){
if (data.result){
data["image"]= "/img/comment-placeholder.png";
//data["$$hashKey"] = "003";
alert("adding element" +$scope.aportaciones.length);
$scope.comments.push(data);
alert("added element" +$scope.aportaciones.length);
}
}
So I run this and I get two alert, one saying "adding element n" and the next "added element n+1" so it appears to reach to $scope.comment_callback an push the data to the array but the DOM is not updated and I cannot see the inserted comment in the page.
I must be something wrong but cannot find what...
I've see the response from ajax and is the same kind of JSON but withouth the $$haskey key.
PD: received data from the ajax service is:
{"username":"inigo","texto":"ggggggggggggggggggggggg","date":"now","result":true,"pk":74,"foto":"/img/agora-placeholder.png"}
The one getted when loading page for that comment (and which is well shown in the page) is:
{"pk":"74","texto":"ggggggggggggggggggggggg","username":"inigo","date":"10/11/14","foto":"/img/agora-placeholder.png"}
You have to wrap the content of comment_callback in a $scope.$apply method to notify about $scope changes within async callbacks:
$scope.comment_callback = function (data){
if (data.result){
$scope.$apply(function() {
data["image"]= "/img/comment-placeholder.png";
$scope.comments.push(data);
});
}
}

Grails chain selects without domains

I'm trying to chain two, possibly three <g:select ...> statements together using Ajax like is shown here Populate dropdown list using ajax In grails but all the examples I find have two big differences from what I'm using. 1. I'm using the jQuery library, not prototype. And 2. I don't have domain objects for my select values, they are pulled from an Oracle table via a service call.
My problem looks like this:
<g:select name="degreeSubject" from="${majors}" noSelection="${['':'-Choose Subject-']}" value="${degreeInstance?.degreeSubject }"/>
<g:select name="degreeConcentration" from="${concentrations}" noSelection="${['':'']}" value="${degreeInstance?.degreeConcentration }"/>
Where the majors, and concentrations come through the controller but are populated in a service class.
I was thinking the controller method would look something like
def updateSelect = {
def concentrations = degreeService.getConcentrations(params.selectedValue)
render (template:"selectConcentration", model : ['concentrations' : concentrations])
}
But, I can't get it to work.
Thoughts? Or someone have an example of doing this with jQuery and no domain objects using Grails 2.2.4?
You can really do it without being javascript-library specific. If you use the grails built-in remoteFunction it will handle the jQuery portion for you. What you would then want for your degreeSubject select is:
<g:select name="degreeSubject"
from="${majors}"
noSelection="${['':'-Choose Subject-']}"
value="${degreeInstance?.degreeSubject }"
onChange="${remoteFunction(
controller: 'yourControllerName',
action: 'updateSelect',
params: '\'value=\' + escape(this.value),
onSuccess: 'updateConcentration(data)')}/>
The key being the onChange event calling the remoteFunction. The remote function will make an ajax call to whatever controller action you want, but you'll need to call a javascript function to take in the results of your controller action and populate the other select. If you wanted to do this with simple js you could do this:
function updateConcentration(items) {
var control = document.getElementById('degreeConcentration')
// Clear all previous options
var i = control.length
while (i > 0) {
i--
control.remove(i)
}
// Rebuild the select
for (i=0; i < items.length; i++) {
var optItem = items[i]
var opt = document.createElement('option');
opt.text = optItem.value
opt.value = optItem.id
try {
control.add(opt, null) // doesn't work in IE
}
catch(ex) {
control.add(opt) // IE only
}
}
}
and finally your controller action should look like this:
def updateSelect(value) = {
def concentrations = degreeService.getConcentrations(value)
render concentrations as JSON // or use respond concentrations if you upgrade to 2.3
}

Showing dynamic links inside a table

In jquery, how can I show a link that is generated on the fly inside a table?
I will have the link stored in my database, but I want it to be shown by a name and then take me to the correct link accordingly.
I have an array of strings like [ {Name1:Link1} ] stored, and I want it to be shown inside the table as Name1 linking to Link1.
Please tell me how to do so.
You need to store them in a (object) map instead of an array.
var linksMap = {
'google': 'http://google.com',
'stackoverflow': 'http://stackoverflow.com',
'jquery': 'http://jquery.com'
};
Then, assuming that you've the following table,
<table id="links">
<tr><td>google</td></tr>
<tr><td>stackoverflow</td></tr>
<tr><td>jquery</td></tr>
</table>
you can use the following jQuery script to create links and put them in the cells:
$('#links>tbody td:nth-child(1)').each(function() {
var $td = $(this);
var name = $td.text();
var link = linksMap[name];
var $a = $('<a>').attr('href', link).text(name);
$td.html($a);
});

Categories