用Angular.js替换<img/> src

时间:2013-04-25 11:24:20

标签: javascript angularjs

我目前正在构建标题图片的幻灯片,然后单击选择并设置该标题图像以替换旧标题图像。到目前为止,这是我的代码:

var app = angular.module('plunker', []);

app.controller('BannerCtrl', function($scope) {  

  var imageCounter = 0;

  $scope.nextButton = function () {
    imageCounter = imageCounter + 1;
    if (imageCounter === 1) {
      $scope.carouselState = 'second-slide';
    }
    if (imageCounter === 2) {
      $scope.carouselState = 'third-slide';
    }
    if (imageCounter > 2) {
      imageCounter = 0;
      $scope.carouselState = 'reset-slide';
    }
  };

  $scope.previousButton = function () {
    imageCounter = imageCounter - 1;
    if (imageCounter < 0) {
      imageCounter = 2;
      $scope.carouselState = 'third-slide';
    }
    if (imageCounter === 1) {
      $scope.carouselState = 'second-slide';
    }
    if (imageCounter === 0) {
      $scope.carouselState = 'reset-slide';
    }
  };

  $scope.setHeader = function () {
    if (imageCounter === 0) {
      $scope.currentbannerImage = '/styles/img/banner-default1.jpg';
      $scope.bannerState = '';
    }
  };

  $scope.currentbannerImage = [
    {
      src: "1.jpg"
    }
  ];

  $scope.bannerImages = [
    {
      src: "2.jpg"
    },
    {
      src: "3.jpg"
    },
    {
      src: "4.jpg"
    }
  ];
});

我还设置了一个Plunker,以展示我的目标!

http://plnkr.co/edit/vRexvso9RvLwyKK1vcKZ

有人可以帮助我用其他'bannerImages'取代'currentBannerImage'吗?

谢谢,

JP

2 个答案:

答案 0 :(得分:11)

您可以使用AngularJS UI Bootstrap通过AngularJS实现轮播(如果您的兴趣是严格的解决方案)。

修改:

我不确定这是不是你想要的,但也许这会有所帮助:http://jsfiddle.net/FKUs3/

<img ng-src="{{availableImages[currentImage].src}}"/>

$scope.currentImage = 0;
$scope.availableImages = [
{
  src: "http://upload.wikimedia.org/wikipedia/commons/thumb/8/80/US_1.svg/50px-US_1.svg.png"
},
{
  src: "http://0.tqn.com/d/painting/1/0/V/_/1/Stencil-Number2a.jpg"
},
{
  src: "http://eminiunderground.com/wp-content/uploads/2012/02/Stencil-Number3a.jpg"
}
];

$scope.nextButton = function() {
  $scope.currentImage++;
  if ($scope.currentImage > ($scope.availableImages.length - 1)) {
    $scope.currentImage = 0;
  }
}
$scope.prevButton = function() {
  $scope.currentImage--;
  if ($scope.currentImage < 0) {
    $scope.currentImage = ($scope.availableImages.length - 1);
  }
} 

答案 1 :(得分:0)

我认为您只需在setHeader上更改currentbannerImage的值:

$scope.setHeader = function () {
    $scope.currentbannerImage = $scope.bannerImages[imageCounter];
};