Adelin
Adelin

Reputation: 18991

How to use angular.element find function to search by JQuery selector ?

describe("create a simple directive", function () {


    var simpleModule = angular.module("directivesSample", []);


    simpleModule.controller('Ctrl2', function ($scope) {
        $scope.format = 'M/d/yy h:mm:ss a';
    });

    simpleModule.directive("myCurrentTime", function ($timeout, dateFilter) {

        return function (scope, element, attr) {
            var format;
            var timeoutId;

            function updateTime() {
                element.text(dateFilter(new Date(), format));
            }

            scope.$watch(attr.myCurrentTime, function (value) {
                format = value;
                updateTime();
            });
            function updateLater() {
                timeoutId = $timeout(function () {
                    updateTime();
                    updateLater();

                }, 1000);
            }

            element.bind('$destroy', function () {
                $timeout.cancel(timeoutId);
            });
            updateLater();
        }


    });


    beforeEach(module('directivesSample'));

    var element = angular.element(

        '<div ng-controller="Ctrl2">Date format:<input ng-model="format"> ' +
            '<hr/>Current time is: ' +
            '<span class="timeout" my-current-time="format" id="timeout-render"></span>' +
            '</div>');

    var directiveScope;
    var scope;
    var linkedElement;
    var linkFunction;

    beforeEach(inject(function ($rootScope, $compile) {
        scope = $rootScope.$new();
        linkFunction = $compile(element);
        linkedElement = linkFunction(scope);
        scope.$apply();
    }));

    it("should define element time out", function () {

    var angularElement = element.find('span'); // <-- element is not returned if set to   var angularElement = element.find('.timeout'); or var angularElement = element.find('#timeout-render'); 

        console.log(angularElement.text());
        expect(angularElement.text()).not.toBe('');
    })

});

Having the above test, why am I unable to search for element by JQuery selector ? I am aware of the limitations in the documentation of find() method.But, I have checked out the angularUI project inspected the the usage of find() function as in here

 var tt = angular.element(elm.find("li > span")[0]);   

and find out that the guys are using find to search element by jQuery elector not only tag name while I am not able to do so. Am I missing something ?

Upvotes: 2

Views: 10051

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22943

That's because the built in jqLite in Angular has only limited support for CSS selectors. But if you include jQuery in a script tag before you include Angular, Angular will see that and use jQuery instead of its jqLite for calls to angular.element().

Upvotes: 5

Related Questions