如何使用angular.element find函数来搜索JQuery选择器?

时间:2013-02-26 14:41:11

标签: angularjs angularjs-directive angular-ui

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('');
    })

});

进行上述测试后,为什么我无法通过JQuery选择器搜索元素?我知道find()方法文档中的limitations。但是,我已经检查了angularUI项目检查了find()函数的用法,如here

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

并且发现这些人正在使用find来搜索jQuery选民的元素,而不仅仅是标签名称而我无法这样做。我错过了什么吗?

1 个答案:

答案 0 :(得分:5)

这是因为Angular内置的jqLit​​e对CSS选择器的支持有限。但是如果在包含Angular之前在脚本标记中包含jQuery,Angular将会看到并使用jQuery代替其jqLit​​e来调用angular.element()。