Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue.

For a clearer understanding, here's an example:

JS:

/* controller-home.js ********************************************************/
app.controller("homeController", function($scope, $http, $state) {
    $scope.heading = "SWITCHES";
    $scope.button1 = "Living Room"
    $scope.button2 = "Kitchen"
    $scope.button3 = "Bathroom"
    $scope.button4 = "Balcony"
    $scope.imageSrc = "LitLamp.png";


    $scope.onOf = function() {
        console.log("Switched");
        if ($scope.imageSrc === "LitLamp.png") {
            $scope.imageSrc = "NotLit.png";
        }

    }
})

HTML:

<div style="text-align: center;">
    <h1 >SWITCHES</h1>
    <div ng-controller="homeController">

        <div style="display:inline-block;">
            <button ng-click="onOf()" class="homeSwitchButton">{{button1}}</button>
            <img class="homeButtonImage" src="{{imageSrc}}" alt="Lamp" >
        </div>

        <div style="display:inline-block;">
            <button ng-click="onOf()" class="homeSwitchButton">{{button2}}</button>
            <img class="homeButtonImage" src="{{imageSrc}}" alt="Lamp" >
        </div>

        <div style="display:inline-block;">
            <button ng-click="onOf()" class="homeSwitchButton">{{button3}}</button>
            <img class="homeButtonImage" src="{{imageSrc}}" alt="Lamp" >
        </div>

        <div style="display:inline-block;">
            <button ng-click="onOf()" class="homeSwitchButton">{{button4}}</button>
            <img class="homeButtonImage" src="{{imageSrc}}" alt="Lamp" >
        </div>

    </div>
</div>

Facing the issue where all images change when clicking any button. Seeking a solution to only change the image below the clicked button and keep the rest unchanged.

Answer №1

The issue at hand arises from the fact that the variable imageSrc is being used for all images. To resolve this, it is recommended to create an object for each individual image.

$scope.images = {
  button1: 'source.png',
  button2: 'source.png',
  button3: 'source.png',
  button4: 'source.png'
}

Within the onOf function, you can specify the name of the button being modified.

$scope.onOf = function(buttonName) {
  if ($scope.images[buttonName] === 'bla.png') {
    $scope.images[buttonName] = 'yay.png';
  }
}

In the HTML, set the images by referencing each property and passing the button name as an argument to onOf.

<div style="display:inline-block;">
   <button ng-click="onOf('button1')" class="homeSwitchButton">{{button1}}</button>
   <img class="homeButtonImage" src="{{images.button1}}" alt="Lamp" >
</div>

Alternatively: Instead of individual objects, you can store the buttons as an array and utilize ng-repeat.

$scope.buttons = [{ name: 'bla', image: 'yay.png'}]

$scope.onOf = function(button) {
  if (button.image === 'yay') {
    ...
  }
}

In the HTML:

<div ng-repeat="button in buttons" style="display:inline-block;">
   <button ng-click="onOf(button)" class="homeSwitchButton">{{button.name}}</button>
   <img class="homeButtonImage" src="{{button.image}}" alt="Lamp" >
</div>

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

What is the best way to initiate a page refresh from a separate component in ReactJS?

As a newcomer to React, I am facing an issue in my CRUD application. I have a Main component and in the List Component, I need to fetch data from the server using an API call. The problem arises when I submit a new item in the Create component - I have to ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Row in Internet Explorer 7

I have a function that reveals hidden rows in a table, which works perfectly in all tested browsers except for IE7. The function is written using Prototype.js. function showInactives(){ var row_list = $$('tr.inactive'); var ck =$('inactive_ ...

Troubleshooting problems with sending data in Jquery Ajax POST Request

I've spent a considerable amount of time searching for a solution to why my post request isn't sending its data to the server. Oddly enough, I can successfully send the request without any data and receive results from the server, but when attemp ...

Assign variable values to ng-switch-when='1' within AngularJS

I am a newcomer to AngularJS and currently implementing: <div class="imageslide" ng-switch='slideshow' ng-animate="'animate'"> <div ng-repeat="img in images"> <div class="slider-content" ng-switch-when='$i ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

Eliminate error messages from multiple input fields within the form by leveraging a directive

Within my form, I have multiple input fields for participant emails: <input name="participant{{$index}}email" type="email" ng-model="participant.email" ng-trim="true" required ng-minlength="1" ng-maxlength="255" ...

Establishing a connection between the socket and the currently authenticated user through socket.io

My website consists of multiple pages, and when a user logs in, I need to establish a connection between their user ID (stored in MongoDB) and the socket for real-time messaging. Currently, user details are saved in the express session variables upon login ...

Tips on passing a variable and API response to the following promise in JavaScript!

Using the initial promise "crypto.model.find()" allows me to store an array of "symbols" ( symbol[] ) from the database and retrieve some IDs that I will utilize to construct a URL for making a request to an API using axios.get(url). Upon receiving a resp ...

Popup form validation for improved data accuracy

Currently, I am working on implementing a LOGIN form within a popup. When the form is submitted, it goes through validations and displays errors if any. However, I am facing a challenge in comparing the submitted login credentials with the database within ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

State variable in Redux is not defined

While there have been numerous similar inquiries on this platform, I haven't been able to find a solution to my particular issue. Below is the React component in question: class MyTransitPage extends Component { componentDidMount() { this.pro ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

The edit functionality in jqGrid does not function properly if custom search parameters are designated

Using the Guriddo jqGrid JS version 5.2.0 implemented here: @license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, [email protected] The code block below showcases an entire self-contained implementation of jqGrid. It inclu ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

What are the recommended practices for utilizing AJAX effectively?

As I dive into learning javascript best practices, I find myself a bit confused. From what I've gathered, the recommended ajax practice is: function doSomething(arg1, arg2) { jQuery.ajax({ var urlink = resourceURL url: urlink, ...

Eliminate forward slashes from the telephone number

I am trying to figure out how to format a USA phone number by removing slashes and brackets. I have searched on Google, but I cannot find the answer. I would like to use regex to achieve this, while keeping the plus sign at the start intact. For example, ...