在ng-repeat&上用.attr()改变src。 ng-click无法正常工作

时间:2017-01-10 17:05:14

标签: jquery angularjs

我已经用ng-repeat加载了图片(图钉)。当有人点击彩色针时,它会变灰,反之亦然。

我的重复是:ng-repeat="note in vm.myData.contactHistoryContainer track by $index"

  <!-- this is where the pin goes -->
  <div class="pin-container">
    <div ng-if="note.pinPush == false">
      <!-- unselected pin -->
      <img class="pin dark{{$index}}" src="app/assets/img/office-material.png" alt="uncolored pin" ng-click="vm.darkPinPress()">
    </div>
    <div ng-if="note.pinPush == true">
      <!-- selected pin -->
      <img class="pin colored{{$index}}" src="app/assets/img/office-material2.png" alt="colored pin" ng-click="vm.pinPress()">
    </div>
  </div>

这些图片上的ng-click转到:

var lightpin = "app/assets/img/office-material2.png";
var darkpin = "app/assets/img/office-material.png";

            function darkPinPress() {
              console.log('dark pin pressed');
              $(this).attr('src', lightpin)
            }

            function pinPress() {
              console.log('colored pin was pressed---');
              $(this).attr('src', darkpin)
            }

有人可以看看,让我知道我搞砸了哪里?两种类型的按钮都会触发console.log

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以简化这样做:

  <div class="pin-container">
    <div>
      <img ng-show="!enabled" src="app/assets/img/office-material.png" alt="uncolored pin" ng-click="enabled=!enabled">
      <img ng-show="enabled" src="app/assets/img/office-material2.png" alt="colored pin" ng-click="enabled=!enabled">
    </div>
  </div>

而且,如果你需要在控制器中调用某个函数,你可以用ng-click方法调用它。

http://jsfiddle.net/MfHa6/1778/

答案 1 :(得分:1)

你不应该使用jQuery来解决你的问题。我已经做了一个吸烟者,所以你可以采取一种方法克服你的问题。 https://plnkr.co/edit/19H8KnyLpzdMbEPX4Oeq?p=preview

<div ng-repeat="note in vm.notes">
  <div ng-click="note.pinPush =  !note.pinPush">
    <div ng-if="note.pinPush">
      <img src="http://www.qygjxz.com/data/out/179/4361592-picture.jpg" style="width:200px;">
    </div>
    <div ng-if="!note.pinPush">
      <img src="http://www.qygjxz.com/data/out/180/4964551-picture.jpg" style="width:200px;">
    </div>
  </div>
</div>

所以基本的想法是每次点击都切换note.pinPush。 ng-if控制要显示的图片。

编辑:点击呼叫控制器的新插件
https://plnkr.co/edit/cRj0SoFWAawGbvCnu1Kv?p=preview

<div ng-repeat="note in vm.notes">
  <div ng-click="vm.noteClicked(note)">
    <div ng-if="note.pinPush">
      <img src="http://www.qygjxz.com/data/out/179/4361592-picture.jpg" style="width:200px;">
    </div>
    <div ng-if="!note.pinPush">
      <img src="http://www.qygjxz.com/data/out/180/4964551-picture.jpg" style="width:200px;">
    </div>
  </div>
</div>

区别在于ng-click:<div ng-click="vm.noteClicked(note)">

注意:src是随机图片