What is the best way to replace an image in a div using Angular?

After studying an example of a directive here, I noticed that they used <a href="#" ... to insert a new image into the container div. I attempted to replicate this functionality in my own directive, but clicking on my images does not change the content of my pictBox div. Is there something missing in my CSS file? Why is the background-image text present there? Here is the code for my directive:

app.directive('smallPictureBox', [function(){
    return {
        restrict: 'CA',
        replace: false,
        transclude: false,
        scope: {
            index: '=index',
            item: '=itemdata'
        },
        template: '<a href="#"><img src="{{item.url}}"/></a>',
        link: function(scope, elem, attrs) {

            if (parseInt(scope.index)==0) {
                angular.element(attrs.options).css({'background-image':'url('+ scope.item.url +')'});
            }

            elem.bind('click', function() {
                var src = elem.find('img').attr('src');

                angular.element(attrs.options).css({'background-image':'url('+ scope.item.url +')'});
            });
        }
    }
}]);

This is what my HTML looks like:

<div class="shadow">
  <div class="pictureBox">
    <div id="pictBox">
      <img ng-src="{{primaryImage.url}}">
    </div>
  </div>
  <div class="lowerPictureBox">
    <div ng-repeat="image in item.images" options='#pictBox' itemdata='image' index="$index"     class="smallPictureBox">
      <img ng-src="{{image.url}}">
    </div>
  </div>
</div>

How can I ensure that clicking on a picture in the lowerPictureBox will display it in the pictureBox?

Answer №1

While I wasn't able to replicate your exact example, I managed to create a small functioning code snippet that showcases an image appearing on top when you click the bottom image. This could be helpful for you.

<!DOCTYPE html>
<html ng-app="demo">

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
  </head>
    <body ng-controller="main">
        <div class="shadow">
  <div class="pictureBox">
    <div id="pictBox">
      <img ng-src="{{primaryImage.url}}">
    </div>
  </div>
  <div class="lowerPictureBox">
   <div small linksrc="primaryImage"></div>
  </div>
</div>
        <script>
            var app = angular.module("demo", []);
            app.controller('main', function ($scope) {
                $scope.primaryImage = { url: '' };
            });
            app.directive('small', [function () {
                return {
                    scope: { src: '=linksrc' },
                    replace:true,
                    template:"<img ng-src='http://angularjs.org/img/AngularJS-small.png'>",
                    link: function (scope, elem, attrs) {
                        elem.bind("click", function () {
                            scope.src.url = 'http://angularjs.org/img/AngularJS-small.png';
                            scope.$apply();
                        });

                    }
                }
            }]);


        </script>
</body>

</html>

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

Conceal the loading image once the AJAX function has been successfully

I've been trying to figure out a way to load heavy images after an ajax call using animated GIF as a pre-loader, but haven't found a satisfactory solution yet. Here's the code snippet I'm currently using: function loadProducts(url) { ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

Why should I set the width of the header to be larger than the body in order to fully cover it?

I've set my header width to 106% to span the entire page length, while the max-width for my body is kept at 95%. body { background-color: #333; max-width: 95%; font-family: ivyjournal, sans-serif; margin: 0; padding: 0; overflow-x: hidd ...

Disabling Javascript in Chrome (-headless) with the help of PHP Webdriver

I am experimenting with using Chrome without JavaScript enabled. I attempted to disable JavaScript by adding the --disable-javascript command line argument. I also tried some experimental options: $options->setExperimentalOption('prefs&a ...

Is there a way to delete both the item and its corresponding key from localStorage?

I have developed a basic application that utilizes localStorage for saving and deleting data. However, I encountered an issue where deleting an item only removes the value but not the key. As a result, when loading all items, the deleted ones appear as nul ...

Tips for changing a div's visibility with radio buttons in jQuery

$(':radio').change(function(event) { var id = $(this).data('id'); $('#' + id).addClass('none').siblings().removeClass('none'); }); .none { display: none; } <script src="https://ajax.googleapis.com/ ...

Creating a reusable Angular directive that encapsulates a jQuery lightbox functionality

Currently, I am attempting to integrate a customized jquery lightbox within an Angular directive. My goal is to create the directive in such a way that it simplifies the usage of the lightbox without modifying the original jquery code, as it is also used i ...

Ways to display JSON in a structured format on an HTML page

Is there a way to display JSON in a formatted view on my html page? The JSON data is coming from a database and I want it to be displayed neatly like the following example: { "crews": [{ "items": [ { "year" : "2013", "boat" ...

Creating a Directive in Vue.js to Limit Input Fields to Numeric Values

After recently diving into Vue.js, I encountered a challenge. I needed an input field that only accepted numeric numbers; any other value entered by the user should be replaced with an empty string. To achieve this functionality, I decided to create a cust ...

Trying to work through solving the issue of accessing document.frames["someframe"].function in Chrome instead of IE

I am encountering an issue with my code that is working in Internet Explorer but not in Chrome. try { top.document.frames["myFrame"].compare(); } catch(err) { alert("This is not executed."); } Any suggestions on how to resolve this compatibility pr ...

Deleting a character creates an error

I am conducting a small experiment with a simple goal: to filter and search for users whose names match the current value typed into an input text field. To implement this functionality, I am using RegExp(). Everything works well except when I delete a cha ...

Experiencing the error message "globals is not defined" despite the fact that the globals variable is already defined

Currently, I am working on reorganizing the routes in my web application. I made the mistake of defining all the routes in index.js, and now I'm facing an unusual issue in some files. I keep getting errors stating that the "globals" variable is undefi ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Finding image input loading

When working with the following code: <input type="image" ... onLoad="this.style.opacity = 1" /> Everything seemed to be functioning well in IE, but encountered an issue in Chrome where the onLoad event failed to trigger upon image load. It's ...

Tips on accessing real-time data from a JSON file

I have been working on this project for a while now and wrote some test scripts. I am using setInterval to update the content every 500 seconds, but I am facing an issue with accessing the input fields. For example, if there is a form with input fields, I ...

Menu options moved to the right of the screen

I am encountering a small issue with my dropdown menu that I can't seem to solve. The first item in the dropdown menu appears correctly, but the second item is slightly shifted to the right. It seems like the margin-right applied to the link may be c ...

What are some creative ways to implement the useState function as a toggle switch in React?

import React, { useEffect, useState } from "react"; import './Menu.css' export default function Menu() { const [classes, setClasses] = useState('container') return ( <div> <p>Click the Me ...

Steps for deploying an ejs website with winscp

I have developed a Node.js web application using ExpressJS, with the main file being app.js. Now I need to publish this website on a domain using WinSCP. However, WinSCP requires an index.html file as the starting point for publishing the site. Is there ...

Transitioning my website to incorporate Angular JS

Recently, I have been exploring AngularJS and I am quite impressed with its features. I am currently developing a website using traditional methods (php, html, css, mysql, some jQuery) and I am considering transitioning to Angular. The reason for this chan ...

When you click on one item in a jQuery selector array, the action is being applied to all elements within the array

I've been working on implementing a cheat function for a minesweeper game that reveals a random non-bomb square (line 279) and its safe neighboring squares (the 8 squares around it without bombs). However, I'm encountering an issue where using $ ...