jonhobbs
jonhobbs

Reputation: 27972

Angular JS and jqLite match node to selector

I'm trying to add a few functions from jQuery into jqLite so that I don't have to load the whole jQuery library with my angular apps. I'm using the technique used by Ben Nadel in this article.

http://www.bennadel.com/blog/2753-creating-jqlite-plugins-in-angularjs.htm

I am running into difficulty implementing a closestChild plugin like this one.

https://github.com/lolmaus/jquery.closestchild/blob/master/jquery.closestchild.js

Obviously I've rewritten is slightly so it looks like this.

JQLite.prototype.closestChild = function(selector) {

            var $children, $results;

            $children = this.children();

            if ($children.length === 0){
                return $();
            }

            $results = $children.filter(selector);

            if ($results.length > 0){
                return $results;
            }
            else{
                return $children.closestChild(selector);
            }

        };

...but it leads to this error.

Error: [jqLite:nosel] http://errors.angularjs.org/1.4.0-rc.0/jqLite/nosel

So, I did a search for the error and found that jqLite isn't able to match with selectors for some reason, only tag names (is this ever useful?). What I can't understand is that it's running alongside Ben's .filter() function from that article which seems to work fine when you give it a selector. That's the exact same function I'm calling in this line.

$results = $children.filter(selector);

So, I guess my question is, is there a way I can loop through $children and see if any of them match the selector which is passed in using plain javascript, or some other workaround?

Upvotes: 1

Views: 891

Answers (1)

Estus Flask
Estus Flask

Reputation: 222855

I'm not sure what are you expecting from 'selector', but selector (as it follows from Ben Nadel's code) is either a callback or DOM node.

So it would be would be

angular.element(document.body)
.find('div')
.closestChild(function(el) {
    var element = angular.element(el);
    console.log(element);
    return !!element.text();
});

jqLite's support of selectors is exactly the same as the manual states: it does only getElementsByTagName and only on find.

For 'heavier' jqLite implementations you can check this and that project (they are quite new, I haven't tried them in work yet, so feel free to share your impressions).

Upvotes: 1

Related Questions