IT story

angularjs에서 이벤트를 트리거 한 요소에 액세스하는 방법은 무엇입니까?

hot-time 2020. 9. 3. 23:42
반응형

angularjs에서 이벤트를 트리거 한 요소에 액세스하는 방법은 무엇입니까?


내 웹 앱에서 Bootstrap과 AngularJS를 모두 사용합니다. 두 사람이 함께 일하는 데 어려움이 있습니다.

속성이있는 요소가 있습니다. data-provide="typeahead"

<input id="searchText" ng-model="searchText" type="text"
       class="input-medium search-query" placeholder="title"
       data-provide="typeahead" ng-change="updateTypeahead()" />

그리고 data-source사용자가 필드에 입력 할 때 속성 을 업데이트하고 싶습니다 . 함수 updateTypeahead가 올바르게 트리거되지만 $('#searchText')AngularJS 방식이 아닌 jQuery 방식 인을 사용하지 않는 한 이벤트를 트리거 한 요소에 액세스 할 수 없습니다 .

AngularJS가 이전 스타일의 JS 모듈과 함께 작동하도록하는 가장 좋은 방법은 무엇입니까?


 updateTypeahead(this)

DOM 요소를 함수에 전달하지 않습니다 updateTypeahead(this). 여기 this에서 범위를 참조합니다. DOM 요소에 액세스하려면 updateTypeahead($event). 콜백 함수에서 DOM 요소를 event.target.

참고 : ng-change 함수는 $ event를 변수로 전달할 수 없습니다.


이벤트를 트리거 한 요소에 액세스하는 일반적인 Angular 방법은 원하는 이벤트에 지시문과 bind ()를 작성하는 것입니다.

app.directive('myChange', function() {
  return function(scope, element) {
    element.bind('change', function() {
      alert('change on ' + element);
    });
  };
});

또는 DDO (아래 @tpartee의 의견에 따라) :

app.directive('myChange', function() {
  return { 
    link:  function link(scope, element) {
      element.bind('change', function() {
        alert('change on ' + element);
      });
    }
  }
});

위의 지시문은 다음과 같이 사용할 수 있습니다.

<input id="searchText" ng-model="searchText" type="text" my-change>

플 런커 .

텍스트 필드에 입력 한 다음 그대로 두거나 흐리게합니다. 변경 콜백 함수가 실행됩니다. 해당 콜백 함수 내에서 element.

일부 내장 지시문은 $ event 객체 전달을 지원합니다. 예 : ng- * click, ng-Mouse *. ng-change는이 이벤트를 지원하지 않습니다.

$ event 개체를 통해 요소를 가져올 수 있지만 :

<button ng-click="clickit($event)">Hello</button>

$scope.clickit = function(e) {
    var elem = angular.element(e.srcElement);
    ...

이것은 "Angular 방식에 대해 깊은" -Misko .


요소에 대한 첫 번째 쓰기 이벤트 처럼 쉽게 얻을 수 있습니다.

ng-focus="myfunction(this)"

and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el = event.target
    console.log(el);
}

I have used it as well.


There is a solution using $element in the controller if you don't want to create another directive for this problem:

appControllers.controller('YourCtrl', ['$scope', '$timeout', '$element',
        function($scope, $timeout, $element) {

    $scope.updateTypeahead = function() {
       // ... some logic here
       $timeout(function() {
           $element[0].getElementsByClassName('search-query')[0].focus();
           // if you have unique id you can use $window instead of $element:
           // $window.document.getElementById('searchText').focus();
       });
    }
}]);

And this will work with ng-change:

<input id="searchText" type="text" class="search-query" ng-change="updateTypeahead()" ng-model="searchText" />

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText


I'm not sure which version you had, but this question was asked for long time ago. Currently with Angular 1.5, I can use the ng-keypress event and debounce function from Lodash to emulate similar behavior like ng-change, so I can capture the $event

<input type="text" ng-keypress="edit($event)" ng-model="myModel">

$scope.edit = _.debounce(function ($event) { console.log("$event", $event) }, 800)


To pass the source element in Angular 5 :

<input #myInput type="text" (change)="someFunction(myInput)">

참고URL : https://stackoverflow.com/questions/12994710/in-angularjs-how-to-access-the-element-that-triggered-the-event

반응형