使用angularjs在图像标记中交换ng-src属性

时间:2015-02-09 07:15:51

标签: javascript jquery html css angularjs

我使用jQuery来交换两个图像的来源,这样,当您单击一个图像时,它的src将与另一个添加为数据属性的图像交换,从而导致图像更改。我不想用angularjs来实现同样的目标。我没有严格的议程,它应该使用src交换技术本身在angularjs中实现相同。任何简单而有效的东西都很好。这是我现有的代码。

jQuery

    $(".side-nav li:nth-child(2)").append("<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'>");
    $("#arrowRotate").click(function() {
        var _this = $(this);
        var current = _this.attr("src");
        var swap = _this.attr("data-swap");
        _this.attr('src', swap).attr("data-swap", current);
        //toggle li's below
        $(".side-nav li:nth-child(3)").toggle();
        $(".side-nav li:nth-child(4)").toggle();
        $(".side_nav_custom li:nth-child(2) a").toggleClass("orangeSwap");
    });  

很容易实现切换部分,我已经在角度(see fiddle)中实现了它。唯一让我烦恼的是src交换部分。我已经设置了一个here.

Angular

的index.html

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.4.0-beta.3" src="https://code.angularjs.org/1.4.0-beta.3/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="swap">
  <div ng-controller="SwapControl">
    <h1>Hello {{myData.names.nameTwo}}!</h1>
    <img ng-click="myData.swapHere()" ng-src="{{myData.images.initialImage}}" alt="image to be swapped">
  </div>
</body>

</html>  

script.js

// Code goes here

var myApp = angular.module("swap", []);

myApp.controller('SwapControl', function($scope) {
  $scope.myData = {};
  $scope.myData.names = {
    nameOne: "Plunker",
    nameTwo: "Thomas"
  };
  $scope.myData.images = {
    initialImage: "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif",
    finalImage: "http://www.omniaceducation.com/Portals/11164/images/small-logo.jpg"
  };
  $scope.myData.swapHere = function() {
    // swaping takes place here
  };
});

1 个答案:

答案 0 :(得分:1)

再向myData.images

添加一个变量
$scope.myData.images = {
    initialImage: "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif",
    finalImage: "http://www.omniaceducation.com/Portals/11164/images/small-logo.jpg",
    current : "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif"
  };
你可以放 ng-src="{{myData.images.initialImage}}"ng-src="{{myData.images.current}}" 然后在你的交换函数里面。

    $scope.myData.swapHere = function() {
        if($scope.myData.images.current === $scope.myData.images.finalImage)
          $scope.myData.images.current = $scope.myData.images.initialImage
        else if($scope.myData.images.current === $scope.myData.images.initialImage) 
          $scope.myData.images.current = $scope.myData.images.finalImage
      };