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

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

A Guide to Integrating Cloudinary Upload Widget in React

I am encountering an issue with the Cloudinary Upload Widget in my React App. The problem arises when I open and close the widget multiple times, causing the app to crash and display the error message: widget.open() is not a function Note: Despite this ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Extending a type by adding properties from separate files using TypeScript

I am faced with a situation where I have a file containing either a type or interface variable (all of which are exported), and I need to add new properties to this variable from different files without using extends. Essentially, making changes to the sam ...

Personalized AWS Cognito: Strategies for Tailoring Input Field Designs

MY CURRENT CHALLENGE: Within my Vue application, I am utilizing the AWS authenticator for managing login and signup processes. However, customizing its style has proven to be difficult due to the structure being built with shadow DOM elements. CURRENT S ...

Is there a way to stop bootstrap popover overflow from spilling out of its container?

I'm currently using Bootstrap's popover feature, but I'm struggling to prevent the popover from overflowing its container. Any suggestions on how to achieve this? Check out the demo on Plunker <!DOCTYPE html> <html> <head&g ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to ...

Issues with Node.js and AJAX

I am having trouble with my ajax request to retrieve data from node.js. The interaction between the two seems off, but I can't pinpoint where the issue lies. Below is the snippet of my ajax get request: $.get('/notificationsNumber', ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

I am looking to modify the visibility of certain select options contingent upon the value within another input field by utilizing ngIf in AngularJS

I am currently utilizing Angularjs 1.x to develop a form with two select fields. Depending on the option selected in the first select, I aim to dynamically show or hide certain options in the second select field. Below is the code snippet for the form: &l ...

When rendering in React, the output of a multidimensional object may appear as undefined

Currently experiencing a challenge with a React application that I am developing. I am attempting to display data on the screen, however, there are instances where an object key is not available. For example: <div> <TableRow> <TableCel ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Select a configuration for binding an array of objects in AngularJS

Plunkr: http://plnkr.co/edit/RgNcSg?p=preview I have a dropdown menu displaying different "locations," which are sourced from an array of objects. Despite setting the object value in my controller, it does not appear selected in the dropdown menu. The HTM ...

"Adding page-specific scripts with the help of nunjucks and express app: A step-by-step guide

What is the most efficient way to manage scripts that are common for all pages and scripts that are specific to certain pages using nunjucks as the template engine and express 4 as the backend framework? --- site --- public |___js |___ script.js (f ...

Retrieving data from a React state in one component and utilizing it in a separate component

Thank you for taking the time to assist me with this challenge. I am currently working on a project that involves creating the state goodData in one component called AddProduct and accessing it in another component named ActionBox, both within the same j ...

Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have: <select id="mySelect"> <option>Volvo</option> <option value="Cat" class="red">Cat</option> <option value="Dog" class="r ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

Submit Form Without Reloading -- and successfully submit it

I'm working on a form submission that triggers AJAX and PHP to load data without the need for page reloading. html/php <form method="POST"> <button type="submit" name="image1"> <button type="submit" name="image2"> <button ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...