Angular not refreshing the view

As a beginner in Angular.js, I feel like I might have missed something small but significant here.

To enhance my understanding of Angular, I am constructing a simple panel to route video sources to various destinations.

I currently have a list of predefined sources and destinations (each destination having two slots). These will eventually be loaded from an API, but for now, they are hardcoded in the JavaScript file.

When I choose a source, the "selectedSource" variable is updated with the clicked source. Then, when I click on a destination slot, that slot's content is set to the "selectedSource" object.

Although the console log indicates that the thumb URL of the slot has been updated, the HTML does not display the new image. I have tried using "apply," but I don't think that's the correct approach.

You can view my simplified code snippet here: http://jsfiddle.net/f4Tgf/

function app($scope, $filter) {
$scope.selectedSource = null;

$scope.sources =  {
    source1 : {id:'source1', thumbUrl:'http://lorempixel.com/100/100/sports/1/'},
    source2 : {id:'source2', thumbUrl:'http://lorempixel.com/100/100/sports/2/'},
    source3 : {id:'source3', thumbUrl:'http://lorempixel.com/100/100/sports/3/'}
}

$scope.destinations = {
    dest1 : {id:'dest1', slots: {slot1 : $scope.sources.source2,slot2 : $scope.sources.source3} }
}

$scope.selectSource = function(source){
    if($scope.selectedSource == source){
        // toggle the selected source off if it is already selected
        $scope.selectedSource = null;
    }else{
        $scope.selectedSource = source;  
    }
}

$scope.selectSlot = function(slot){
    slot = $scope.selectedSource;
    console.log(slot.thumbUrl);

    //reset selected source
    $scope.selectedSource = null;
}
}

HTML:

<body >
<div ng-app ng-controller="app" class="container-fluid">
    <div class="row">





        <!-- SOURCES -->
        <div id="source-container" class="col-xs-6">
            <div class="panel panel-default">
                <div class="panel-heading">
                     <h3 class="panel-title">Sources</h3>

                </div>
                <div class="panel-body row">
                    <!-- Show all sources -->
                    <div ng-repeat="source in sources" ng-class="{selected: source==selectedSource}" ng-click="selectSource(source)" class="col-md-6 col-sm-12">
                        <div class="thumbnail">
                            <img class="img-responsive" src="{{source.thumbUrl}}" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- SOURCES -->


        <!-- DESTINATIONS -->
        <div id="sink-container" class="col-xs-6">
            <div class="panel panel-default">
                <div class="panel-heading">
                     <h3 class="panel-title">Destination</h3>

                </div>
                <div class="panel-body row">
                    <!-- Show all destinations -->
                    <div ng-repeat="destination in destinations" ng-class="{available: selectedSource!=null}">
                        <div class="thumbnail">
                            <div ng-repeat="slot in destination.slots" ng-click="selectSlot(slot)">
                                <img class="img-responsive" src="{{slot.thumbUrl}}" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- END DESTINATIONS -->


    </div>
</div>
</body>

(Before advising me to use services or other advanced concepts, please remember that this project serves as my initial learning experience.)

Answer №1

An issue arises when attempting to modify the value parameter, slot, in the selectSlot() function instead of the actual array of destination slots. Given that there can be multiple destination slots within a list of destinations, the most viable solution would involve altering selectSlot() to accept the current array of destination slots along with the specific slot key intended for modification.

To accomplish this task, make a simple alteration to the HTML code:

<div ng-repeat="(key, slot) in destination.slots" ng-click="selectSlot(destination.slots, key)">

Consequently, define your JAVASCRIPT selectSlot() function as follows:

$scope.selectSlot = function(slots, key){
    slots[key] = $scope.selectedSource;

    //Reset selected source
    $scope.selectedSource = null;
}

For a live demonstration, refer to this UPDATED FIDDLE.

Note: To gain further insight into the (key, value) syntax implementation within ng-repeat, consult AngularJS' documentation.

Answer №2

Looks like we're dealing with a JavaScript challenge here.

Within your selectSlot() function:

slot = $scope.selectedSource;

This code snippet doesn't actually assign $scope.selectedSource to one of the slots in $scope.destinations.dest1.slots as you intended.

You might want to try it this way instead:

    slot.id = $scope.selectedSource.id;
    slot.thumbUrl = $scope.selectedSource.thumbUrl;

That should do the trick.

Just keep in mind that in your scenario, you're initializing $scope.destinations.dest1.slots with two objects from $scope.sources, meaning any changes made to a slot in $scope.destinations.dest1.slots will also affect the corresponding one in $scope.sources. This setup should work fine if, as you mentioned, the destinations are "going to be loaded from an API later on".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

What is the best way to show a div after successfully sending a post value using AJAX?

How do I show this specific div after a successful AJAX post? This is what I want to display: <div class="love" id="love_0" style="border-radius: 3px; padding: 8px; border: 1px solid #ccc; right: 13px; background: #fff; top: 13px;"> <a class ...

Issue: Module '@angular/compiler' not found

After downloading an angular template, I encountered an issue while running "ng serve": Cannot find module '@angular/compiler' Error: Cannot find module '@angular/compiler' ... I tried various solutions found on the internet, incl ...

React App folders are not being properly installed through NPX

Encountering an error message while attempting to use npx create-react-app Husna@LAPTOP-LPCC954R MINGW64 ~/Desktop/React GitHib Project (master) $ npx create-react-app github2020 Creating a new React app in C:\Users\Husna\Desktop\Reac ...

Exploring the depths of angular views with the powerful ui.router

Can someone guide me on how to implement login in the index and info in login using ui.router in Angular? I want to display different views based on the URL being used. For instance, when logging in and accessing the driver view, I want the HTML to be inj ...

Disable the monthly navigation feature in the uib-datepicker

Is there a way to disable or remove the month/year navigation button on the Angular uib-datepicker component? We are struggling to find a solution to prevent users from clicking on the "Month/Year" text located between the navigation arrows. You can find m ...

Triggering events on multiple elements with Vue.js when clicked

I am currently working on a feature that involves hiding and showing descriptions of image thumbnails when clicked by the user. I tried following a VueJS tutorial on transitions, but unfortunately only one thumbnail is properly functioning while the rest a ...

Modify the background hue of the added tr element

When adding rows to a table, I have a condition to check if the current date and time fall within the range specified by the start and end date and times of each row. If this condition is met, I need to update the background color of the row. $('# ...

Uncertainty surrounding the distinction between global variables (var) and block variables (let, const) in Node.js

It's common knowledge that var is a global variable in node js and can be accessed from anywhere. However, I found myself perplexed by the following examples: In the first example, accessing global_1 poses no issues as it is a global variable. var g ...

Conditionally updating states, efficiently setting and modifying state with a variety of conditions for optimal performance

Optimizing the updating of react states based on specific conditions can be challenging when dealing with a large number of states. Is there a method in react js to dynamically add and remove states based on certain conditions? For example, if we have an ...

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Generate an additional element for each element when clicked, triggering an error warning

When creating a form, I want to display an error message next to each invalid element when the submit button is clicked. Although I am close, the issue is that it adds the span tag twice after the element if two elements are invalid. I need it to be added ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

Exploring elements in Javascript

I am attempting to retrieve values from various elements when a 'a' element is clicked. Consider the following code: <tr data-id="20"> <div class="row"> <td> <div class="btn-group"> <a data-checked= ...

Anticipated input should be in the format of '_item_ in _collection_[ track by _id_]' but instead received

Having trouble with ng-repeat in AngularJS, only showing first element and getting a console error: Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '”pm'. angular.module('DataCabinet') .c ...

Discovering the specific object ID that triggered an event in JavaScript

I am developing a webpage that includes JavaScript functionality. There is a specific function in the Javascript code which gets triggered by two different elements when clicked: 1. When a checkbox is clicked: $('#chkShowAll').click( functi ...

Retrieve JSON details for various games including their properties

I am currently working on a project that involves accessing Casino Games and their properties from a JSON object to display them on a website. Here is my progress so far: var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?for ...