SOunit / angularjs-memo

1 stars 0 forks source link

fetch dom in angularjs #15

Open SOunit opened 5 months ago

SOunit commented 5 months ago

should use $element.get to avoid duplicate key

In AngularJS, the $element service is used to access the DOM element that the directive is attached to. This service is only available within a directive's link or compile functions, or within a controller if you inject it.

Given your example:

<div ng-app="app" ng-controller="someController">
  <div class="target1"></div>
</div>

<div class="target2"></div>

Understanding $element in AngularJS

  1. Scope of $element: $element provides a reference to the DOM element associated with the current AngularJS directive or controller. In the case of a controller, $element refers to the element on which the controller is declared (e.g., the <div> with ng-controller="someController").

  2. Accessing elements inside the controller's scope:

    • If you use $element inside someController, it will reference the <div ng-controller="someController"> element.
    • To access child elements within this scope, you can use standard jQuery or AngularJS/jqLite methods on $element.

Example with $element:

app.controller('someController', function($scope, $element) {
  // $element refers to the div with ng-controller="someController"
  console.log($element); // Logs the ng-controller div element

  // Find the child element with class 'target1'
  var target1 = $element.find('.target1');
  console.log(target1); // Logs the target1 div element
});

Accessing elements outside the controller's scope:

$element in the context of someController cannot directly access the <div class="target2"></div> element, as it is outside the scope of the controller. However, you can access it using standard DOM or jQuery methods if necessary.

Example using jQuery or AngularJS/jqLite:

app.controller('someController', function($scope, $element) {
  // To access elements outside the controller's scope:
  var target2 = angular.element(document.querySelector('.target2'));
  console.log(target2); // Logs the target2 div element
});

Summary

So, in your specific example, to fetch the <div class="target2"></div> element, you would need to use:

var target2 = angular.element(document.querySelector('.target2'));

This approach allows you to fetch DOM elements that are outside the immediate scope of the AngularJS controller or directive where $element is used.