Guide on dynamically assigning the value of an Angular variable to another variable

My website has a slideshow feature with left and right buttons, similar to this example: .

I am using Angular to change the image when the left or right button is clicked.

In the function, I am incrementing a value:

    /*SlideShow Pictures*/
$scope.picture_1 = "./images/photos/watch.jpg";
$scope.picture_2 = "./images/photos/watch.jpg";
$scope.picture_3 = "./images/photos/watch.jpg";
$scope.picture_4 = "./images/photos/watch.jpg";
$scope.picture = $scope.picture_1;
$scope.picture_value = 1;

$scope.image_change_right = function () {
    if ($scope.picture_value < 4)
    {
       $scope.picture_value = $scope.picture_value + 1;
       $scope.picture = ('$scope.picture_' + $scope.picture_value);
       console.log($scope.picture_value);
    }
    else{

        $scope.picture_value = 1;
        $scope.picture = ('$scope.picture_' + $scope.picture_value);
        console.log($scope.picture_value);
    }
}

This function is triggered when the right button is pressed.

The issue is that even though the value is correctly shown in the console log, it seems like it is being treated as a string rather than a variable. How can I ensure that the value is assigned to the scope.picture variable correctly?

Any help or advice would be greatly appreciated. Thank you!

Answer №1

Here is an improved method:

The Controller:

// Array containing links to pictures.
$scope.pictures = [
  "./images/photos/watch.jpg",
  "./images/photos/watch.jpg",
  "./images/photos/watch.jpg",
  "./images/photos/watch.jpg"
];

$scope.current = 0; // Initialize the current picture index.
$scope.picture = $scope.pictures[$scope.current]; // Set the current picture.

// The direction is either 1 or -1;
$scope.changePicture = function (direction) {
  $scope.current += direction; // Increment or decrement based on direction.
  $scope.current %= $scope.pictures.length; // Ensure index stays within bounds.
  console.log($scope.picture);
}

The Html:

<img src="{{picture}}">

<button ng-click="changePicture(1)">Next</button>
<button ng-click="changePicture(-1)">Previous</button>

Answer №2

Have you considered using an array to store image links for your slideshow?

   /*Image Slideshow Setup*/
$scope.images = ["./images/slideshow/image1.jpg", "./images/slideshow/image2.jpg", "./images/slideshow/image3.jpg", "./images/slideshow/image4.jpg"];
$scope.currentImage = $scope.images[0];
$scope.imageIndex = 0;

$scope.changeImage = function () {
    if ($scope.imageIndex < 4)
    {
       $scope.imageIndex = $scope.imageIndex + 1;
       $scope.currentImage = $scope.images[$scope.imageIndex];
       console.log($scope.imageIndex);
    }
    else{

        $scope.imageIndex = 0;
        $scope.currentImage = $scope.images[$scope.imageIndex];
        console.log($scope.imageIndex);
    }
}

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

The caret operator in NPM does not automatically install the latest minor version of a package

Within my package.json file, one of the dependencies listed is labeled as... "@packageXXX": "^0.7.0", Upon running the "npm outdated" command, I observed that... @packageXXX current: 0.7.0 wanted: 0.7.0 latest: 0.8.0 Despite executing "npm ...

exchange information among distinct domains

Two distinct services are operating on separate machines, resulting in different URLs for each service. The user initially accesses the front end of the first service. Upon clicking a button on this service, the user is directed to another front end servi ...

Ways to invoke a function from a service in AngularJS?

My focus is on learning AngularJS, and I recently came across this particular section. However, I am struggling to comprehend why the batchLog service is being invoked in this manner! Although the batchLog service is designed with only one method named lo ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

navigating between html pages using sliding next and previous buttons

I am in the process of developing a multi-page form spread across 4 different pages. I would like to incorporate next and previous buttons to allow users to easily navigate through the form. Although I have tried looking online for solutions, most results ...

Which regular expression should be used to validate names with international characters?

Currently in my PHP project using Codeigniter, I am implementing form validation. Specifically, I have configured the validation rules for the name field like this: $this->form_validation->set_rules('name', 'Nombre', 'requir ...

What steps can be taken to revert this Node.js module to a particular version and ensure it does not automatically update in

While using the Nodemailer module in node.js, I encountered a specific error that read as follows; [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 or see the migration guide https://github.com/andris9/Nodemailer#migration-guide] A ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Tips on integrating a series of typical utility directives into an Angular module

If we have a collection of versatile angular directives, such as one that ignores non-numeric characters when typed, how can we best organize and include them in our Angular modules? Should we create a separate module, like Foo, to house these directives? ...

Is sendFile causing an error due to an invalid JSON format?

Whenever I try to send a file to a client for download, I encounter an exception saying that the JSON is invalid. Is there a better way to send the file, perhaps using res.download and setting the content as JSON? I want to avoid using AngularJS FileSaver ...

When an unrelated value is changed, the Vue 2 dynamic component experiences a loss of its values during the refresh

I've been grappling with this issue for quite some time now and I'm beginning to suspect it might be a bug. I'm currently utilizing a dynamic vue component to substitute markers in a body of text with input fields. The functionality seems t ...

Having trouble with Angular JS functionality

Today is my first day diving into AngularJS and I'm eager to learn more! Despite grasping the concept of how model-controller-views operate in AngularJS, I encountered an issue where the variables are not displaying as expected. Instead of the values, ...

Ways to display and conceal a div when hovering over another div

Currently, I have 4 divs grouped under the class "menubut." I am attempting to create a small overlay that appears when hovering over the menubut classes. Additionally, I want another div called "red" to show up about one-tenth of the size of the menubut ...

What are the steps to build a dynamic webpage in a Django project?

For my Django app, I have successfully created static pages without any ajax requests. However, I now want to add a dynamic subpage that can change its content without refreshing or reloading the entire page. Let me explain what I'm trying to achieve ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Tips for managing the 'completed' button in an Android keyboard application using AngularJS/Ionic

Currently, I am working on developing a hybrid mobile application using AngularJS, Cordova, and the Ionic framework. Check out this Android 5.0 keyboard with a distinct blue button located at the bottom-right corner. https://i.stack.imgur.com/Tfija.png ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...