Utilize the same service logic for a pair of identical buttons

I have a method in my ReverseService service. I am using this service in my controller. When calling it with ng-click, the issue arises where the same function is being executed for two different buttons instead of just one. Although I understand why this is happening, I am struggling to find a solution. Below is the code snippet.
HTML

<div id="sidebar" ng-controller="SideCtrl">
            <!-- static sidebar content -->
            <div class="large_3_custom columns">
                <ul class="side-nav side_nav_custom">
                    <li>
                        <img src="images/dashboard.png" alt="">
                        <a href="#">DASHBOARD</a>
                    </li>
                    <li>
                        <img ng-src="images/company_profile.png" alt="">
                        <a href="#">COMPANY PROFILE</a>
                        <img ng-src="{{images.current}}" ng-click="swapHere();subSec = !subSec" id="arrowRotate">
                    </li>
                    <li ng-show="subSec">
                        <img src="" alt="">
                        <a href="#">SERVICES</a>
                    </li>
                    <li ng-show="subSec">
                        <img src="" alt="">
                        <a href="#">EMPLOYEES</a>
                    </li>
                    <li>
                        <img src="images/statistics.png" alt="">
                        <a href="#">STATISTICS</a>
                    </li>
                    <li>
                        <img src="images/reviews.png" alt="">
                        <a href="#">REVIEWS</a>
                    </li>
                    <li>
                        <img src="images/tips_advice.png" alt="">
                        <a href="#">TIPS & ADVICE</a>
                    </li>
                    <li>
                        <img src="images/deals.png" alt="">
                        <a href="#">DEALS</a>
                    </li>
                    <li>
                        <img src="images/media.png" alt="">
                        <a href="#">MEDIA</a>
                    </li>
                    <li>
                        <img src="images/price_list.png" alt="">
                        <a href="#">BOOKING</a>
                        <img ng-src="{{images.current}}" ng-click="swapHere();bookSec = !bookSec" id="arrowBook">
                    </li>
                    <li ng-show="bookSec">
                        <img src="" alt="">
                        <a href="#">CALENDAR</a>
                    </li>
                    <li>
                        <img src="images/market.png" alt="">
                        <a href="#">MARKET</a>
                    </li>
                    <li>
                        <img src="images/sponser_deal.png" alt="">
                        <a href="#">SPONSOR A DEAL</a>
                    </li>
                    <li>
                        <img src="images/extra_services.png" alt="">
                        <a href="#">EXTRA SERVICES</a>
                    </li>
                </ul>
            </div>
        </div>  

Angular

var myApp = angular.module("myApp", []);
myApp.service("ReverseService", function() {
    // service function implementation --
    this.imgSwap = function(images) {
        if (images.current === images.finalImage) {
            images.current = images.initialImage;
        } else if (images.current === images.initialImage) {
            images.current = images.finalImage;
        }
    };
});
myApp.controller("SideCtrl", function($scope, ReverseService) {
    console.log("thomas");
    $scope.myData = {};
    $scope.images = {
        initialImage: "images/prof_arrow1.png",
        finalImage: "images/prof_arrow.png",
        current: "images/prof_arrow1.png"
    };
    $scope.swapHere = function() {
        ReverseService.imgSwap($scope.images);
    };
    $scope.subSec = false;
    $scope.bookSec = false;
});

Check out the Plunker demo.

Answer №1

Ensure the scope is isolated for the images' value.

I've made updates to the Plunk: Take a look

To achieve this, you should implement a directive with an isolated scope and controller. Feel free to adjust the CSS to align the image correctly: I've added a template file (swapimage.html)

<img src="{{displayImage}}" ng-click="imageClicked()">

Here's the directive:

myApp.directive("swapArrow", function(ReverseService){
  return {
    restrict:'A',
    scope : {
      images :'=',
      toggleValue : '='
    },
    templateUrl:'swapimage.html',
    controller:function($scope, ReverseService){
      $scope.imageClicked = function(){
        ReverseService.imgSwap($scope.images); 
        $scope.displayImage = $scope.images.current;
        $scope.toggleValue = !$scope.toggleValue;
        console.log($scope.toggleValue);
      };

    },
    link:function(scope, element){
      scope.displayImage = scope.images.current;
    }
  }
});

Instead of manipulating a toggleValue, I recommend using transclusion for content manipulation along with show/hide functionality

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

Creating a hover effect instead of a click event in a Bootstrap 4 dropdown menu

Looking to create a hover effect instead of a click in the bootstrap dropdown menu? Past answers lack jQuery code that can simply be copied and pasted into your script for optimal results. Additionally, previous solutions were written for older versions o ...

Sharing data between different sections of Jade templates in Express 3

Currently, I am utilizing Express 3.0 with Jade as the template engine. My goal is to transfer a variable from a template page to the primary layout page. Here's an example of what I'm attempting: Snippet from layout.jade: !!! 5 html(lang=&apos ...

The use of JSON.parse does not support parsing URL links

As a junior developer specializing in Javascript and Google Apps Script, I decided to enhance the functionality of my Google Sheets by tracking the last modification time of URLs stored in them. Although I attempted to create a script for this task, it see ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

What is the best way to adjust a number up or down by one with the push of a button?

Is there a way I can increment and decrement the number 12 by one each time I press the + and - buttons? Additionally, if I have other buttons that need to perform the same function, do I need to assign them the same class name and will they work in the sa ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

Exploring ways to loop through a state array in React and strategically delaying each iteration based on conditions

Project: Currently, I am in the process of developing a Chatbot and my goal is to display the Chatbot messages sequentially with a delay between each message. Challenge: The messages are stored in a state array. Previously, I utilized map within the JSX o ...

I am facing a recurring issue where I am unable to add new libraries to my node_modules directory due to encountering the same error every time I attempt to

An error occurred after running npm audit --force, causing a dependency issue in my Node_modules 0 verbose cli C:\Program Files\nodejs\node.exe C:\Users\Jenis\AppData\Roaming\npm\node_modules\npm\bin& ...

What could be causing the issue with the .toLocaleTimeString method not properly converting time zones?

I have been attempting to convert timezones based on the current time, but I haven't had success. I tried switching from using date.toLocaleTimeString to date.toLocaleString, but it didn't work. I also tried changing the timezone from America/Den ...

Determining the Number of Sub-Menu Items Using jQuery without Reliance on CSS Classes

I've scoured the depths of Google and SO in search of answers, but nothing quite fits the bill. My mission is to create a submenu without using classes, adding a style attribute to each individual <li> within the sub <ul> that sets a min- ...

Switching Bootstrap Navbar Active State with JavaScript

I have encountered an issue with using the "active" class on my navbar navigation items in Bootstrap 4. When I click on the links, the active state does not switch as intended. I have tried incorporating JavaScript solutions from similar questions but have ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

The content in Angular UI Grid fails to display until the browser window is adjusted

I am currently utilizing angularjs 1.5.0 along with angular ui grid 3.1.1. In my controller, I assign the gridOptions object (which is passed to the grid directive) in the following way: $scope.gridOptions = { data: [{"mock2": 1, "mock1": 2}, {"moc ...

Using Javascript to interact with a two-dimensional JSON array

Similar Question: I have a nested data structure / JSON, how can I access a specific value? While working with the US Census API, I encountered a two-dimensional JSON array after making a request using jQuery.get(). The result (data) resembles the fol ...

When attempting to access a Google Apps Script URL for a deployed WebApp, a 404 error is encountered

This issue is very similar to others (like the problem with Google Drive mentioned on this Stack Overflow post) that have been discussed here. Although not identical, I believe it stems from the same core issue highlighted in that thread. The issue arises ...

Conceal User Interface Angular Tabulation

I'm working on setting up UI Bootstrap tabs, and for reference you can find the plunker here. My goal is to hide the tabs since I will be utilizing a button to switch between them. Despite adding the following CSS class to my file, the styling is not ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...