加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – isolationScope()在使用templateUrl时返回undefine

发布时间:2020-12-17 08:04:26 所属栏目:安全 来源:网络整理
导读:我有一个指令,我想要单元测试,但我遇到的问题,我无法访问我的孤立的范围。这是指令: my-directive/my-directive 和它背后的代码: angular.module('demoApp.directives').directive('myDirective',function($log) { return { restrict: 'E',templateUrl:
我有一个指令,我想要单元测试,但我遇到的问题,我无法访问我的孤立的范围。这是指令:
<my-directive></my-directive>

和它背后的代码:

angular.module('demoApp.directives').directive('myDirective',function($log) {
    return {
        restrict: 'E',templateUrl: 'views/directives/my-directive.html',scope: {},link: function($scope,iElement,iAttrs) {
            $scope.save = function() {
                $log.log('Save data');
            };

        }

    };
});

这是我的单元测试:

describe('Directive: myDirective',function() {
    var $compile,$scope,$log;

    beforeEach(function() {
        // Load template using a Karma preprocessor (http://tylerhenkel.com/how-to-test-directives-that-use-templateurl/)
        module('views/directives/my-directive.html');
        module('demoApp.directives');
        inject(function(_$compile_,_$rootScope_,_$log_) {
            $compile = _$compile_;
            $scope = _$rootScope_.$new();
            $log = _$log_;
            spyOn($log,'log');
        });
    });

    it('should work',function() {
        var el = $compile('<my-directive></my-directive>')($scope);
        console.log('Isolated scope:',el.isolateScope());
        el.isolateScope().save();
        expect($log.log).toHaveBeenCalled();
    });
});

但是当我打印出孤立的范围时,会导致未定义。真正让我感到困惑的是,如果不使用templateUrl,我只需在我的指令中使用模板,那么一切都有效:isolationScope()有一个完整的scope对象作为其返回值,一切都很好。然而,不知何故,当使用templateUrl时,它会中断。这是一个在mo-mocks或者Karma预处理器中的错误?

提前致谢。

我有同样的问题。看来,当使用templateUrl调用$ compile(element)($ scope)时,摘要循环不会自动启动。所以你需要手动设置它:
it('should work',function() {
    var el = $compile('<my-directive></my-directive>')($scope);
    $scope.$digest();    // Ensure changes are propagated
    console.log('Isolated scope:',el.isolateScope());
    el.isolateScope().save();
    expect($log.log).toHaveBeenCalled();
});

我不知道为什么$ compile函数不会为你做这个,但它必须是一些与templateUrl的工作方式相似的特性,因为你不需要调用$ scope。$ digest()if你使用内联模板。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读