gpt4 book ai didi

javascript - 如何动态地将 Angular 变量的值设置为另一个变量

转载 作者:行者123 更新时间:2023-11-28 11:32:18 25 4
gpt4 key购买 nike

我的网站上有一个带有左右按钮的幻灯片。像这样(http://i.prntscr.com/863ad10cfd4e4f1ea9b90721cc6582e8.png)。

我正在使用 Angular 来更改左侧和右侧的图像。

正如你在函数中看到的,我增加了值

    /*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);
}
}

以上是按钮右键调用的函数。

该函数将变量加1并将其添加到字符串中以调用新变量。在控制台日志中看起来很棒!不过我认为它只是显示为字符串 --- 它实际上并未将 range.picture 的值设置为变量。

如何将其设置为有效变量而不是字符串?

谢谢大家!

最佳答案

更好的方法是这样的:

Controller :

// The array of picture links.
$scope.pictures = [
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg"
];

$scope.current = 0; // Initialize the current pictures place in the array.
$scope.picture = $scope.pictures[$scope.current]; // Set the current picture.

// The direction is either 1 or -1;
$scope.changePicture = function (direction) {
$scope.current += direction; // add or remove one depending on direction.
$scope.current %= $scope.pictures.length; // Normalize the number based on the length of the pictures array.
console.log($scope.picture);
}

HTML:

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

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

关于javascript - 如何动态地将 Angular 变量的值设置为另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39343796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com