ng-click 可以获取父 div 的 id 作为参数吗?

Can ng-click get the id of the parent div as parameter?

当我得到以下例子时:

<div id="a-div-id">
    <img ng-src="{{image.image}}" ng-click="select(image.id)" />
</div>

我能否以某种方式将 div 元素的 ID a-div-id 作为参数传递给 ng-click 函数 select()?否则我将不得不将 div 的 ID 存储在我的图像对象中。那可不太好。

是的,您可以访问 $event

来自angular documentation

$event Directives like ngClick and ngFocus expose a $event object within the scope of that expression. The object is an instance of a jQuery Event Object when jQuery is present or a similar jqLite object.

因此您的代码如下所示:

$scope.select= function(imageId, clickEvent) {
      $scope.myParentId= clickEvent.target.parentElement.id;
      $scope.mySelectedImageId = imageId;
    };

我做了一个plnkr where you can reproduce it

不使用控制器也可以:

<div ng-init="theId = 'hello'" id="{{theId}}">
   <img ng-src="{{image.image}}" ng-click="select(theId)" />
</div>

JSFiddle