Changing the ng-src attribute with a custom service in an AngularJS application

Check out this Pluker I created for making image swapping easier. Currently, the images swap normally when coded in the controller. However, I am interested in utilizing custom services or factories to achieve the same functionality. Below is the code snippet.
HTML

<body ng-app="myApp">
    <!-- navigation bar -->
    <div id="navBar">
        <!-- dynamic navbar goes here -->
    </div>
    <!-- end of navigation bar -->
    <div class="row fullWidth">
        <!-- sidebar begins -->
        <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 src="images/company_profile.png" alt="">
                        <a href="#">COMPANY PROFILE</a>
                        <img ng-click="myData.swapHere();subSec = !subSec" id="arrowRotate" ng-src="{{myData.images.current}}">
                    </li>
                    <li ng-show="subSec">
                        <img src="" alt="">
                        <a href="#">SERVICES</a>
                    </li>(more on plunker)  

Angular

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

Your help is much appreciated!

Answer №1

The issue at hand is related to passing strings into the service function, causing them to get unboxed and not treated as reference types.

One possible solution would be to pass the images object directly into your services function.

myApp.service("ReverseService", function() {
    // Define the service method here --
    this.imgSwap = function(images) {
        if (images.current === images.initial) {
            images.current = images.final;
        } else if (images.current === images.final) {
            images.current = images.initial;
        }
    }
})

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

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Connect your Nuxt.js application with Mailchimp for seamless integration

I've tried the solution recommended in this thread, but unfortunately, it's not working for me. Every time I run npm run dev, I encounter an error message: ERROR - Compilation failed with 1 error at 11:21:24 The following dependency was not fo ...

Issue with connecting to server causing difficulty in downloading files using AngularJS

The data fetched from the server is displayed here. viewApp.controller('perInfor',['$scope','$http',function($scope,$http){ $scope.viewPerson = function(id){ console.log(id); $http({ method:'get', ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...

What causes Node.js to be unable to handle requests from Vue.js?

I'm encountering a strange error where Node.js is unable to see the URL address and consistently returns a 404 error. In my Vue.js application, I am making a post request using the axios package when the user clicks a button. The code snippet shows t ...

What is the best way to navigate to a specific location on a web page?

After clicking the "Add comment" link, a comment form popped up using Ajax. I now need assistance with scrolling to it, can you please help me out? ...

What is the best way to incorporate a button that can toggle the visibility of the sidebar on my post page?

Check out this post of mine I noticed a button on someone's page that could hide their sidebar and expand it again when clicked. How can I implement this feature? Is it a simple task? ...

What are the steps for creating the yeoman "angular-generator" application for production?

My angular application was initially created using "yeoman" with the command "yo angular" and included grunt sass bootstrap, resulting in a project size of 200mo when including all dev features like node_modules and bower_components. I am looking for guid ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Harmonizing database with AJAX-powered webpage

When using ajax calls to update data on a web page, what is the most effective way to synchronize changes with a database? For example, if I have a comment form that needs to work asynchronously. I write JS code to submit the form data to the database, but ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Guide to utilizing a shared route function across various routes in express.js

Is there a way to handle the scenario where I need both www.example.com/12345/xxxxx and www.example.com/xxxxx to trigger the same function in my application using Express? app.get('/:someVar/xxxxx', function(req, res) { /* etc */ }); I can acce ...

What is the best method for eliminating script tags from a Magento web store's source code?

Below is the source code for the Magento site's homepage. I am looking to eliminate all JavaScript links from the code: ...

How can you retrieve input radio button values using javascript or ajax and display or hide a button accordingly?

I've created a form that includes radio input buttons and a textarea field as follows: <input type="radio" value="2" id="order_status"> Review <input type="radio" value="1" id="order_status"> Accept <input type="radio" value="2" id="or ...

The application monitored by nodemon has halted - awaiting modifications in files before restarting the process

1. My ProductController Implementation: const Product = require('../models/product') //Creating a new product => /ap1/v1/product/new exports.newProduct = async(req, res, next) => { const product = await Product.create(req.body); re ...

Incorporating input fields into an HTML form

I'm looking to enhance my form by adding input fields dynamically through the JavaScript function when I click on the add button: let i = 0; function increment() { i += 1; } function addFieldFunction() { let newDiv = document.createElement(&apos ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...