Having issues with ng-src and images not loading in the application

Is there a way to dynamically change the image source using ng-src? I've been attempting to switch the image file source based on an onclick event using the code below, but it's not working as expected.

<html ng-app="ui.bootstrap.demo">
    <body>
        <pre>{{checkModel}}</pre>
        <div class="btn-group">
            <!--            Add DB names to label -->
            <label class="btn btn-primary" ng-model="checkModel.left" ng-click="toggleImage()" btn-checkbox><img ng-src="{{imageSwapUrl}}"  />Left</label>
            <label class="btn btn-primary" ng-model="checkModel.middle" btn-checkbox><img id="dbIcon"  src="images/database-5-16.ico" />Middle</label>
            <label class="btn btn-primary" ng-model="checkModel.right" btn-checkbox><img id="dbIcon"  src="images/database-5-16.ico" />Right</label>
        </div>
        <?php
        // put your code here
        ?>
        <script>
            angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
            angular.module('ui.bootstrap.demo').controller('ButtonsCtrl', function ($scope) {
                $scope.imageSwapUrl = "images/database-5-16.ico";
                $scope.checkModel = {
                    left: false,
                    middle: true,
                    right: false

                };
                $scope.toggleImage = function () {
                    if ($scope.imageSwapUrl === 'images/database-5-16.ico') {
                        $scope.imageSwapUrl = 'images/accept-database-16.ico';
                    } else {
                        $scope.imageSwapUrl = 'images/database-5-16.ico';
                    }
                }




            });
        </script>
    </body>

</html>

When testing the code above, the initial image file doesn't load, and I don't see any errors in the console log. Can anyone point out why this might be happening?

Answer №1

A controller named ButtonsCtrl was created in your javascript code, but it was not utilized within your HTML markup. Therefore, the functions within the controller will not be executed.

<body ng-controller="ButtonsCtrl">
    .....
</body>

Answer №2

Please define the controller before using it

<html ng-app="custom.app">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
  <script type="text/javascript" src="assets/js/ui-bootstrap-tpls-2.5.0.min.js"></script>
  <style>
    img#customIcon {
      margin: -1px 0px 0px;
      position: absolute;
      top: 2px;
      left: 1px;
    }

    label.btn.btn-primary {
      width: 65px;
    }
  </style>
  <title>Custom App</title>
</head>

<body ng-controller="CustomCtrl">
  <pre>{{customData}}</pre>
  <div class="btn-group">
    <label class="btn btn-primary" ng-model="customData.left" ng-click="toggleIcon()" btn-checkbox><img ng-src="{{iconUrl}}" />Left</label>
    <label class="btn btn-primary" ng-model="customData.center" btn-checkbox><img id="customIcon" src="assets/images/icon.png" />Center</label>
    <label class="btn btn-primary" ng-model="customData.right" btn-checkbox><img id="customIcon" src="assets/images/icon.png" />Right</label>
  </div>
  <script>
    angular.module('custom.app', ['ui.bootstrap']);
    angular.module('custom.app').controller('CustomCtrl', function($scope) {
      $scope.iconUrl = "assets/images/icon.png";
      $scope.customData = {
        left: false,
        center: true,
        right: false
      };
      $scope.toggleIcon = function() {
        if ($scope.iconUrl === 'assets/images/icon.png') {
          $scope.iconUrl = 'assets/images/other-icon.png';
        } else {
          $scope.iconUrl = 'assets/images/icon.png';
        }
      }
    });
  </script>
</body>
</html>

View the live demo here for reference

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

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

AngularJS - ensuring that updates in child contexts are reflected in the parent context

I am currently working on an AngularJS application that includes a shell page. The shell page has a dropdown menu that lists various locations. Within one of the internal pages, there is a feature that allows users to add new locations. Once a new location ...

Utilizing "this" correctly within JavaScript objects

Can someone help me understand how to access enums.ROCK within the prop in the code snippet below? I keep getting an error that says Uncaught TypeError: Cannot read property 'enums' of undefined. Please pay attention to the comment ERROR LINE. c ...

Troubleshooting problem with populating data in Mongoose Database

Here is the code snippet: app.get("/cart", checkAuthentication, function (req, res) { Orders.find({ user: req.user._id }) .populate('user') .populate('order') .exec((err, orders) => { console.log(orders); ...

Generating div elements dynamically and applying styles

Generating a div dynamically and adding style to it var newDiv = document.createElement('div'); newDiv.setAttribute("id","dynamic-div"); document.body.appendChild(newDiv); // Simulating dynamic ajax content loading $(document).ready(function () ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

Using React Router can sometimes lead to an issue where the React components are

My server side rendering is set up for performance, but I am encountering discrepancies between the client and server renderings. The client initially renders <!-- react-empty: 1 --> instead of components, which leads to a different checksum. As a re ...

Import JSON Data into Angular-nvD3 Chart (AngularJS)

I am seeking help to load encoded JSON Data retrieved from a database via queries into an Angular-nvD3 graph. I am unsure about the best approach to achieve this task. The encoded JSON data is fetched using API queries from a database table called PRODUCT ...

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

Using NodeJS in conjunction with Nginx

Running both NodeJS and Nginx on the same server has posed a unique challenge for me. I have successfully configured Nginx to handle requests from "www.example.com" while also wanting NodeJS to take requests from "api.example.com". The setup is almost comp ...

Modify the colors of <a> elements with JavaScript

I am brand new to the world of UI design. I am encountering an issue with a static HTML page. (Please note that we are not utilizing any JavaScript frameworks in my project. Please provide assistance using pure JavaScript code) What I would like to achie ...

Sharing details of html elements using ng-click (AngularJS)

I am currently exploring options to enable users to click on a "open in new tab" link, which would essentially transfer that HTML element into a fresh window for their convenience. I am seeking advice on how to achieve this. At the moment, I am able to la ...

Enable users to handle the version of a dependency in an npm package

As I develop a module that relies on THREE.js, I am exploring the most effective method to include THREE as a dependency and ensure accessibility for both the module and its users. My goal is to provide users with access to the THREE library within their p ...

`The universal functionality of body background blur is inconsistent and needs improvement.`

I've developed a modal that blurs the background when the modal window is opened. It's functioning flawlessly with one set of HTML codes, but encountering issues with another set of HTML codes (which seems odd considering the identical CSS and Ja ...

I'm having trouble displaying the X's and O's in my tic tac toe JavaScript game. Any suggestions on how to resolve this issue?

After following a couple of online tutorials for the tic tac toe project, I encountered an error in both attempts. The X's and O's were not displaying even though all other features were working fine. Below are my codes for HTML, CSS, and JavaScr ...

Strategies for effectively managing numerous API requests

My current setup involves fetching about five API calls simultaneously. While it works at times, most of the time it results in a fetch error. Is there a way to prevent these errors from occurring when running the API calls? app.post("/movie/:movieN ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...