ng-if在ng-repeat中重新创建点击事件的元素

时间:2016-02-29 04:21:41

标签: javascript jquery angularjs if-statement dom

当用户点击它时,我想用img替换锚标签。 我的示例代码就像

<div ng-repeat="postpart in currentPost.parts ">



   <div ng-if = "!postpart.isclicked">
          <img ng-src="{{imgurl}}" ng-click="iclicked(postpart)"/>
   </div>

   <div ng-if = "postpart.isclicked">
       <a ng-href="{{postpart.description}}" ng-init="init()"></a>
   </div>



</div>

iclicked函数只是使isclicked为true。

它完美地适用于一部分。 但当有2个部分时,它显示2个图像。 当我点击它时,它会被一个锚元素替换。

但是在第二张图片的情况下,它会替换为2个锚标签。

我怎么能成功呢? 是否有任何解决方案在ng-repeat中用锚替换图像元素?

1 个答案:

答案 0 :(得分:1)

可能会帮到你。

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

app.controller("ctrl" , function($scope){
  
  $scope.parts = [
    {"description": "This is a test","isclicked":false,"type":"MEDIA"},
    {"description": "This is a test2","isclicked":false,"type":"MEDIA"},
    {"description": "This is a test3","isclicked":false,"type":"MEDIA"},
    {"description": "This is a test4","isclicked":false,"type":"MEDIA"}
  
  ];
    
  $scope.iclicked = function(index){
    $scope.parts[index].isclicked = !$scope.parts[index].isclicked;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">  
  <div ng-repeat="part in parts">
    <div ng-show = "!part.isclicked">
      <img src="/images/1.png" ng-click="iclicked($index)"/>
    </div>

    <div ng-show = "part.isclicked">
      <a href="part.description" >{{part.description}}</a>
    </div>
  </div>
</div>