簡體   English   中英

使用AngularJS獲取父容器的DOM元素屬性

[英]Get DOM element attribute of parent container with AngularJS

我是AngularJS的新手,我嘗試實現以下目標:在單擊某些外部元素以及單擊其子元素時,我想獲取外部元素的某些屬性。

在jQuery中,當我單擊子元素時,這似乎很容易冒出來。 在Angular中,調用了我在外部元素上進行“ ng-click”操作的函數,但是無法獲取該屬性。我在這里將Angular和jQuery的示例放在這里: http : //www.allcontrasts.com /external/angular-jquery/index.html

關鍵代碼如下:

HTML:

<body ng-app="testApp" ng-controller="testController" >
  <div class="angulardiv" ng-click="myAlert($event);" data-id="321">ANGULAR
    <div class="sublement">
        Subelement
    </div>
  </div>
  <div class="jquerydiv" data-id="321">JQUERY
    <div class="sublement">
        Subelement
    </div>
  </div>
</body>

角度代碼:

var app = angular.module('testApp', []);
app.controller('testController', function($scope) {
    $scope.myAlert = function(event) {
        var elem = angular.element(event.target);
        var dataId = elem.attr('data-id');
        alert(dataId);
    }
});

jQuery的:

$(document).ready(function() {
    $('.jquerydiv').click(function() {
        alert($(this).attr('data-id'));
    })
});

在這種情況下,如何使用Angular實現jQuery的功能?

好的,在這種情況下,靈魂化非常容易,我可以將HTML更改為:

<div class="angulardiv" ng-click="myAlert(321);">ANGULAR
  <div class="sublement">
     Subelement
  </div>
</div>

...只是將所需的ID直接作為參數傳遞給函數。

然后將“角度代碼”更改為:

var app = angular.module('testApp', []);
app.controller('testController', function($scope) {
    $scope.myAlert = function(obj) {
        alert(obj);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM