Dynamically change img ng-repeat using firebase - javascript

I have a page where a teacher can select a class (of school students). Then the teacher can create groups of students from this class by dragging avatars of the students.
I have a drop down list of classes and a div filled with avatars of the students.
The HTML:
<select name="chosenClass" onchange="chooseClass(this.value)">
<option ng-repeat="(key, value) in techerClasses">{{key}}</option>
</select>
...
<div id="div0" ondrop="drop(event)" ondragover="allowDrop(event)" class="groupDiv">
<img ng-repeat="(key, value) in classStudents" id={{key}} src="http://placehold.it/30x30/{{value}}" draggable="true" ondragstart="drag(event)">
</div>
The controller code:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classesRef.child(classInfo).on('value', function (dataSnapshot){
$rootScope.classStudents = dataSnapshot.val().members;
});
}
}
If I add data manually to the $rootScope.classStudents before
the page loads the avatars will show correctly.
console.log($rootScope.classStudents) after
$rootScope.classStudents = dataSnapshot.val().members; confirms
that the right data is in there.
But the avatars are not showing.
If I click "back" in the browser and then "forward" - the avatars
will show. This leads me to think that I need something that will
tell the <img ng-repeat... to refresh?

You're missing a $rootScope.$apply as you've done something outside of angular:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classesRef.child(classInfo).on('value', function (dataSnapshot){
$rootScope.classStudents = dataSnapshot.val().members;
$rootScope.$apply();
});
}
}
Alternatively look into using $firebaseArray:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classStudents = $firebaseArray($rootScope.classesRef.child(classInfo).child('members'))
}
}

set src="http://placehold.it/30x30/{{value}}" to ng-src="http://placehold.it/30x30/{{value}}" to add the src attribute to the digest.
Also $rootScope.$apply or $timeout(angular.noop) if you need a "save digest"

Related

How do I access images depends on notification type

I stored notificationType in back end json file, And in notifacation controller i have stored same notificationtype with name and images(which images it supposed to show depends on notification type) for to compare.
Now i would like to acces the images depends on notification type.
i had tried like this but its taking only 0th position images it is taking.
I got to know what my mistake is but i dont know how to do it can anyone help me...
my code is.
controller.js
$scope.typeofnotification =[{name:'offer', imges: './resources/remote.png'},
{name:'discount', imges:'./resources/mic.png'},
{name:'upgrades', imges:'./resources/play-icon.png'}];
/*var len = $scope.typeofnotification.length*/
$scope.setNotificationImage = function(){
var notificationImage;
for (var i = 0; i < $scope.typeofnotification.length; i++)
{
if($scope.notificationData[i].notificationType == $scope.typeofnotification[i].name)
{
return notificationImage = $scope.typeofnotification[i].imges;
}
}
};
notificationData[i].notificationType this line from backend
one.HTML
<div class="notifications" ng-repeat="item in notificationData">
<img id="notificationImages" yo-src="setNotificationImage()"/>
<div id="notificationdata" yo-attr="{html: 'item.desc'}"></div>
<div id="notificationdate" yo-attr="{html: 'item.date'}"></div>
</div>
In the ng-repeat directive notificationdata comes from backend
output what i am getting is, only 1st image oth position image i am getting for all notification.
but i want images depends on notification type.
as for above code, If notification type is add_content it needs to display remote.png and if type is 'discount' it needs to display mic.png and finaly if typeis upgrades it needs to display play-icon.png
plz check images below.
enter image description here
In your solution you only get same value because of when satisfied first condition return that image url not your item image url.
you need to check with repeated item instead of $scope.notificationData so need to pass item when call setNotificationImage function and check with this item.notificationType === $scope.typeofnotification[i].name
like:
HTML:
<div class="notifications" ng-repeat="item in notificationData">
<img id="notificationImages" yo-src="setNotificationImage(item)"/> //pass item
<div id="notificationdata" yo-attr="{html: 'item.desc'}"></div>
<div id="notificationdate" yo-attr="{html: 'item.date'}"></div>
</div>
Controller:
$scope.setNotificationImage = function(item){
for (var i = 0; i < $scope.typeofnotification.length; i++)
{
if(item.notificationType === $scope.typeofnotification[i].name)
{
return $scope.typeofnotification[i].imges;
}
}
};

Update unrelated field when clicking Angular checkbox

I have a list of checkboxes for people, and I need to trigger an event that will display information about each person selected in another area of the view. I am getting the event to run in my controller and updating the array of staff information. However, the view is not updated with this information. I think this is probably some kind of scope issue, but cannot find anything that works. I have tried adding a $watch, my code seems to think that is already running. I have also tried adding a directive, but nothing in there seems to make this work any better. I am very, very new to Angular and do not know where to look for help on this.
My view includes the following:
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<fieldset>
<p data-ng-repeat="person in staffCtrl.persons">
<input type="checkbox" name="selectedPersons" value="{{ physician.StaffNumber }}" data-ng-model="person.isSelected"
data-ng-checked="isSelected(person.StaffNumber)" data-ng-change="staffCtrl.toggleSelection(person.StaffNumber)" />
{{ person.LastName }}, {{ person.FirstName }}<br />
</p>
</fieldset>
</div>
<div data-ng-controller="staffController as staffCtrl">
# of items: <span data-ng-bind="staffCtrl.infoList.length"></span>
<ul>
<li data-ng-repeat="info in staffCtrl.infoList">
<span data-ng-bind="info.staffInfoItem1"></span>
</li>
</ul>
</div>
My controller includes the following:
function getStaffInfo(staffId, date) {
staffService.getStaffInfoById(staffId)
.then(success)
.catch(failed);
function success(data) {
if (!self.infoList.length > 0) {
self.infoList = [];
}
var staffItems = { staffId: staffNumber, info: data };
self.infoList.push(staffItems);
}
function failed(err) {
self.errorMessage = err;
}
}
self.toggleSelection = function toggleSelection(staffId) {
var idx = self.selectedStaff.indexOf(staffId);
// is currently selected
if (idx >= 0) {
self.selectedStaff.splice(idx, 1);
removeInfoForStaff(staffId);
} else {
self.selectedStaff.push(staffId);
getStaffInfo(staffId);
}
};
Thanks in advance!!
In the code you posted, there are two main problems. One in the template, and one in the controller logic.
Your template is the following :
<div data-ng-controller="staffController as staffCtrl" id="providerList" class="scrollDiv">
<!-- ngRepeat where you select the persons -->
</div>
<div data-ng-controller="staffController as staffCtrl">
<!-- ngRepeat where you show persons info -->
</div>
Here, you declared twice the controller, therefore, you have two instances of it. When you select the persons, you are storing the info in the data structures of the first instance. But the part of the view that displays the infos is working with other instances of the data structures, that are undefined or empty. The controller should be declared on a parent element of the two divs.
The second mistake is the following :
if (!self.infoList.length > 0) {
self.infoList = [];
}
You probably meant :
if (!self.infoList) {
self.infoList = [];
}
which could be rewrited as :
self.infoList = self.infoList || [];

Replacing divs that can be replaced in html/javascript

Hi i'm trying to replace some divs with other divs, this works fine but when i try to replace the second load of divs they don't change anymore.
Basicaly I'm trying to create a "winetour" that lets a user choose some options and generates the perfect wine to go along with it.
You get presented with a couple of options (img links) and if you click one the div's content changes and presents another set of clickable images taking you deeper in your process of choosing a great wine.
HTML:
<div id"Gelegenheid">
<img src="Images/Ontbijt.jpg" id="ontbijt" alt="Ontbijt">
<img src="Images/Borrel.jpg" id="borrel" alt="Borrel">
<img src="Images/Dinner.jpg" id="feest" alt="Diner">
<img src="Images/Feest.jpg" id="diner" alt="Feest">
</div>
<div id"Ontbijt" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Borrel" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Dinner" style="display: none">
<img src="Images/White.jpeg" id="ontbijt-licht" alt="ontbijt-licht">
</div>
<div id"Dinner-detail-voor" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Dinner-detail-head" style="display: none"> Some content that shows trough the "tour"</div>
JavaScript:
function continueTour(i) {
if (i==1) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Ontbijt").innerHTML;
} else if (i==2) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Borrel").innerHTML;
} else if (i==3) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Diner").innerHTML;
} else if (i==4) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Feest").innerHTML;
} else {
document.getElementById("Dinner").innerHTML = document.getElementById("Dinner-detail-voor").innerHTML;
}
}
So basically if you click on a link that's inside the "Gelegenheid" div you will be taken to for example Dinner, but the problem is, inside dinner there are some more links and i want to link them for example to "Dinner-detail-voor"
I want to make this working with core JavaScript (so no JQuery) but i don't know what's going on?
Thanks in advance!
Found the answer.
Added
document.getElementById("from").style.display = "none" ;
document.getElementById("to").style.display = "table" ;
to each of the javscript index functions, now it works where 'from' is the father and 'to' is the child that is being linked to, not very neat but it works,
If someone has a shorter or alternative solution feel free to post!
first we create an array for all the content, array is base 0 so we start from function myFunction(0); next we create a tag with updated variable in them. the if statement is use to reset the variable when hit max. hope this help.
http://jsfiddle.net/xgay3f83/3/
function continueTour(i) {
var content = ['content 1', 'content 2', 'content 3', 'content 4'];
var target = document.getElementById('target');
var next = i + 1;
var end = content.length;
if(next>end) {
i = 0;
next = 1;
}
var openTag = '<a href="#" class="hvr-grow" onClick = "continueTour('+next+')">';
var closeTag = '</a>';
target.innerHTML = openTag+content[i]+closeTag;
}

Javascript show/hide multiple DIV's

I'm in need of a bit of help. I have a current script that switches div's between being visible and hidden depending on a dropdown selector, it works as it was originally designed absolutely fine.
The problem i have is that i need to modify it to change more than 1 div on the page. Currently i'm using the same ID for the div's but only the first item on the page is updated. Reading over the JS this makes sense, but i can't figure out how to modify it to get the desired result?
Javascript:
var lastDiv = "";
var lastProd = "";
function showDiv(divName, productID) {
if (productID == lastProd) {
$("#"+lastDiv).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
}
else {
$(".visible-div-"+productID).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
}
lastProd = productID;
lastDiv = divName;
}
The selector:
<select onchange="showDiv('pxo_'+this.value,2);" name="pre_xo_id">
<option value="3">Blue - £120.00</option>
<option value="4">Red - £120.00</option>
<option value="5">Yellow - £120.00</option>
The DIV's:
<div id="pxo_3" class="visible-div-2" style="display: none;">RED</div>
<div id="pxo_4" class="hidden-div visible-div-2" style="display: none;">BLUE</div>
<div id="pxo_5" class="hidden-div visible-div-2" style="display: block;">YELLOW</div>
<div id="pxo_3" class="visible-div-2" style="display: none;">1 In Stock</div>
<div id="pxo_4" class="hidden-div visible-div-2" style="display: none;">1 In Stock</div>
<div id="pxo_5" class="hidden-div visible-div-2" style="display: none;">0 In Stock</div>
id's must be unique, that's why only the first item is being update. You may put those values to class instead to allow multiple selection.
First you can not use one id for morethan one element.They must be unique.Apply same css class to those elements.
We can use same class instead to allow multiple selection.
IDs are supposed to be used for only a single element on the page. You want to use css selectors.
Thank you for the help all, I have modified the JS to look for both ID and Class as i am unable to change part of the code due to it being protected by ioncube.
This seems to have the desired result:
var lastDiv = "";
var lastProd = "";
function showDiv(divName, productID) {
if (productID == lastProd) {
$("#"+lastDiv).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
$("."+lastDiv).hide();
$("."+divName).fadeIn(".visible-div-"+productID);
} else {
$(".visible-div-"+productID).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
$(".visible-div-"+productID).hide();
$("."+divName).fadeIn(".visible-div-"+productID);
}
lastProd = productID;
lastDiv = divName;
}

Javascript onclick change variable value

I am new to JavaScript and I need some help. I am making a website and I have several images of team members that if clicked (so I'm guessing the onclick event) will change the variable values corresponding to that team member. For instance, if I click on a picture of Bill Gates, in a separate div, I need to have a variable (let's say Name) change value to Bill Gates. Then, if I click on an image of Steve Jobs, the variables containing Bill Gates' data will get overwritten with the data of Steve Jobs. How do I do this?
Assuming mark-up like the following:
<div id="gallery">
<img class="people" data-subject="Steve Jobs" src="path/to/imageOfSteve.png" />
<img class="people" data-subject="Bill Gates" src="path/to/imageOfBill.png" />
</div>
<span id="caption"></span>
Then a relatively simple, and plain JavaScript, approach:
function identifySubject(image, targetEl) {
if (!image) {
return false;
}
else {
var targetNode = document.getElementById(targetEl) || document.getElementById('caption'),
person = image.getAttribute('data-subject');
text = document.createTextNode(person);
if (targetNode.firstChild.nodeType == 3) {
targetNode.firstChild.nodeValue = person;
}
else {
targetNode.appendChild(text);
}
}
}
var images = document.getElementsByClassName('people');
for (var i=0, len=images.length; i<len; i++) {
images[i].onclick = function(e){
identifySubject(this, 'caption');
};
}
JS Fiddle demo.
Onclick attribute is right. You need to add the name of a javascript function to the image's onclick attribute (eg <img src="" onclick="changeVariable()"...).
If you want text on the page to change depending on who you click on, you'll need to look at selecting divs in Javascript using getElementById() or similar and look at the InnerHTML property.
See: http://woork.blogspot.co.uk/2007/10/how-to-change-text-using-javascript.html
Hope this helps
<img src="path/to/image1" onclick="getValue('bill gates')" />
<img src="path/to/image2" onclick="getValue('steve jobs')"/>
<div id="show_value"></div>
<script>
function getValue(val){
document.getElementById('show_value').innerHTML = val
}
</script>
HTML:
<div class="member"><img src="billgates.jpg" /><span>Bill Gates bla bla</span></div>
<div class="member"><img src="stevejobs.jpg" /><span>Steve Jobs bla bla</span></div>
<div id="variables"></div>
JS:
$(function(){
$('.member img').click(function(){
$('#variables').html($(this).closest('span').html());
});
});

Categories