angularjs
  • angularjs-directive
  • angular-ui
  • 2013-02-26 59 views 2 likes 
    2
    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()method.But文档中的limitations,我已经签出了angularUI项目考察发现的使用()函数中here如何使用angular.element查找函数通过JQuery选择器进行搜索?

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

    ,并发现该人是使用find来通过jQuery elector搜索元素不仅可以标记名称,而且我也不能这样做。我错过了什么吗?

    回答

    5

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

    +0

    我已经在testacular.conf.js中包含jQuery(我想这应该包含它),但仍然无法工作! – Adelin 2013-02-26 14:57:56

    +0

    但是,你的答案似乎是合理的! – Adelin 2013-02-26 14:58:34

    +0

    您必须在测试前明确包含它以避免竞争条件。 – 2013-04-04 22:55:31

    相关问题