AngularJS - Find Element with attribute

前端 未结 3 1703
南方客
南方客 2020-12-23 10:05

I\'m new to AngularJS. I\'ve learned that I can find elements in the DOM using queries like the following:

var e = angular.element(document.querySelector(\'#         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 10:39

    You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

    If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

    So, for this HTML:

    this one

    This AngularJS code should work:

    angular.module('MyClient').controller('MyCtrl', [
        '$scope',
        '$element',
        '$log',
        function ($scope, $element, $log) {
    
            // Find the element by its class attribute, within your controller's scope
            var myElements = $element.find('.myElementClass');
    
            // myElements is now an array of jQuery DOM elements
    
            if (myElements.length == 0) {
                // Not found. Are you sure you've included the full jQuery?
            } else {
                // There should only be one, and it will be element 0
                $log.debug(myElements[0].name); // "foo"
            }
    
        }
    ]);
    

提交回复
热议问题