如何动态地将角度变量的值设置为另一个变量

时间:2016-09-06 08:09:43

标签: javascript angularjs

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

我使用角度来改变左右两侧的图像。

正如您在函数中看到的那样,我增加了值

    /*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并将其添加到字符串以调用新变量。在控制台日志中它看起来很棒!但是我认为它只显示为字符串---它实际上并没有将scope.picture的值设置为变量。

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

谢谢大家!

2 个答案:

答案 0 :(得分:6)

更好的方法是:

控制器:

ed06d686-8a04-4ae1-9500-975fb85a49d9

Html:

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

答案 1 :(得分:1)

为什么不使用像这样的图像链接的数组?

   /*SlideShow Pictures*/
$scope.pictures = ["./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg"];
$scope.picture = $scope.pictures[0];
$scope.picture_value = 0;

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

        $scope.picture_value = 0;
        $scope.picture = $scope.pictures[$scope.picture_value];
        console.log($scope.picture_value);
    }
}