【问题标题】:AngularJS jasmine isolateScope() returns undefinedAngularJS jasmine isolateScope() 返回未定义
【发布时间】:2014-10-28 18:31:01
【问题描述】:

我希望从我的 help-button 指令中的孤立作用域中得到一些东西。

  it('should contain proper scope, depending on attributes', function() {

        var el = compile('<help-button context-id="1"></help-button>')(scope);
        scope.$digest();


        console.log("el: " + el);
        console.log('Isolated scope: ' + el.isolateScope());
   ..
   });

-- 在每次测试之前

beforeEach(inject(function($compile, $rootScope, $injector) {

    compile = $compile;
    scope = $rootScope.$new(); ...

打印出来:

'el: [Object Object]'
'Isolated scope: undefined'

问题是:为什么我会返回 undefined?即使隔离范围内没有任何内容,它仍然应该是空的 {} 对象。但无论如何 - 测试是错误的 - 它没有显示(实际)包含数据的隔离范围。

【问题讨论】:

    标签: javascript angularjs scope jasmine


    【解决方案1】:

    我很笨。

    但会回答我自己的问题,因为“一个愚蠢的人就像愚蠢一样” - 即可能曾经会做同样的事情(或者将来为我自己)。

    问题出在我的指令正在使用的helpbutton.html 中(我没有在这个问题中显示/提及)。

    所以templateUrl 指的是应该正确编译为html 的helpbutton.html 文件。

    当我查看el.html() 的输出时,我发现它没有正确呈现(有一些缺失的标签或其他东西)。

    这就是为什么我无法从element 获得任何scope

    (虽然如果模板没有正确呈现为 html,那么在日志中出现某种异常会很好)

    【讨论】:

    • 那么你是如何解决你的 html 问题的?
    • 您应该将自己的答案标记为正确答案。
    【解决方案2】:

    刚刚遇到同样的问题,但原因不同。以防万一其他人有同样的问题,这可能是你以前见过的,但仍然很明显。

    如果您使用的是 templateUrl,那么 .isolateScope() 函数将返回 undefined,直到您真正调用了 .$digest 和 $httpBackend.flush();

    当你直接使用指令中的模板时,它会在你执行 $compile(element)(scope) 的那一刻可用。

    如果您刚刚将指令更改为使用 templateUrl,或者将其从常规更改为isolateScope,这可能会让您大吃一惊。

            responseHtml = '<div></div>';
            $httpBackend.expectGET('template.html').respond(200, responseHtml);
    
            var html = '<widget></widget>';
            element = angular.element(html);
            var compiled = $compile(element)(scope);
    
            console.log(element.isolateScope()); // undefined
    
            $rootScope.$digest();
    
            console.log(element.isolateScope()); // undefined
    
            $httpBackend.flush();
    
            console.log(element.isolateScope()); // now it will be available
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多