jQuery find() method not working in AngularJS directive

前端 未结 7 986
说谎
说谎 2021-01-31 14:26

I am having trouble with angularjs directives finding child DOM elements with the injected angular element.

For example I have a directive like so:



        
相关标签:
7条回答
  • 2021-01-31 15:09

    find() - Limited to lookups by tag name you can see more information https://docs.angularjs.org/api/ng/function/angular.element

    Also you can access by name or id or call please following example:

    angular.element(document.querySelector('#txtName')).attr('class', 'error');
    
    0 讨论(0)
  • 2021-01-31 15:10

    I used

    elm.children('.class-name-or-whatever') 
    

    to get children of the current element

    0 讨论(0)
  • 2021-01-31 15:16

    Before the days of jQuery you would use:

       document.getElementById('findmebyid');
    

    If this one line will save you an entire jQuery library, it might be worth while using it instead.

    For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.

    // Fast:
    $( "#container div.robotarm" );
    
    // Super-fast:
    $( "#container" ).find( "div.robotarm" );
    

    http://learn.jquery.com/performance/optimize-selectors/

    jsPerf http://jsperf.com/jquery-selector-benchmark/32

    0 讨论(0)
  • 2021-01-31 15:19

    You can easily solve that in 2 steps:

    1- Reach the child element using querySelector like that: var target = element[0].querySelector('tbody tr:first-child td')

    2- Transform it to an angular.element object again by doing: var targetElement = angular.element(target)

    You will then have access to all expected methods on the targetElement variable.

    0 讨论(0)
  • 2021-01-31 15:30

    If anyone is looking to grab the scope off of a 'controller as' element,.. something like this:

    <div id="firstctrl" ng-controller="firstCtrl as vm">  
    

    use the following:

    var vm = angular.element(document.querySelector('#firstctrl')).scope().vm;
    
    0 讨论(0)
  • 2021-01-31 15:30

    You can do it like this:

     var myApp = angular.module('myApp', [])
      .controller('Ctrl', ['$scope', function($scope) {
         $scope.aaa = 3432
     }])
     .directive('test', function () {
        return {
           link: function (scope, elm, attr) {
               var look = elm.children('#findme').addClass("addedclass");
               console.log(look);
            }
       };
    });
    
    <div ng-app="myApp" ng-controller="Ctrl">
       <div test>TEST Div
          <div id="findme">{{aaa}}</div>
       </div>
    </div>
    

    http://jsfiddle.net/FZGKA/133/

    0 讨论(0)
提交回复
热议问题