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

angularjs – 测试 – 如果使用$compile

发布时间:2020-12-17 09:17:57 所属栏目:安全 来源:网络整理
导读:我试图通过根据预定义范围编译视图并运行$scope $$digest来测试我的一个模板中的ng-if. 我发现编译的模板出来是一样的,不管我的情况是真实的还是假的.我会期望编译的html删除ng-if dom元素时,falsy. beforeEach(module('templates'));beforeEach(inject(func
我试图通过根据预定义范围编译视图并运行$scope $$digest来测试我的一个模板中的ng-if.

我发现编译的模板出来是一样的,不管我的情况是真实的还是假的.我会期望编译的html删除ng-if dom元素时,falsy.

beforeEach(module('templates'));
beforeEach(inject(function($injector,$rootScope){
    $compile = $injector.get('$compile');
    $templateCache = $injector.get('$templateCache');
    $scope = $rootScope.$new();
    template = angular.element($templateCache.get('myTemplate.tpl.html'));
}));

afterEach(function(){
    $templateCache.removeAll();
});

it ('my test',function(){
    $scope.myCondition = true;
    $compile(template)($scope);
    $scope.$digest();


    expect(template.text()).toContain("my dom text");
    // true and false conditions both have the same effect
});

这是一个plunkr试图显示发生了什么(不知道如何测试在plunkr,所以我在控制器中完成)http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=preview

当ngIf放置在模板的根元素上时,会出现一个可能的问题.
ngIf删除节点并在其中放置注释.然后,它会观察表达式,并根据需要添加/删除实际的HTML元素.问题似乎是,如果它放置在模板的根元素上,那么一个注释就是从整个模板中留下的(即使只是暂时的),这被忽略了(我不知道这是否是浏览器 – 具体行为),导致一个空模板.

如果确实如此,您可以将您的ngIfed元素包含在< div&gt ;:::

<div><h1 ng-if="test">Hello,world !</h1></div>

另见这个short demo.

另一个可能的错误是以空白模板结尾,因为它不存在于$templateCache中.即如果你不把它放在$templateCache中,那么以下代码将返回undefined(产生一个空的元素):

$templateCache.get('myTemplate.tpl.html')

(编辑:李大同)

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

    推荐文章
      热点阅读