测试NG-如果使用$编译 [英] Testing ng-if using $compile

查看:166
本文介绍了测试NG-如果使用$编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试一个NG-如果由编译视图针对pre定义的范围和运行$范围。$消化我的模板之一。

I'm attempting to test an ng-if in one of my templates by compiling the view against a pre-defined scope and running $scope.$digest.

我发现,编译模板,无论我的病情是否truthy或falsy出来的一样。我期望编译的HTML删除NG-如果DOM元素时falsy。

I'm finding that the compiled template is coming out the same regardless of whether my condition is truthy or falsy. I would expect the compiled html remove the ng-if dom elements when 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测试,所以我在控制器完成吧)<一个href=\"http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=$p$pview\">http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=$p$pview

Here's a plunkr attempting to show what's happening (not sure how to test in plunkr, so I've done it in a controller) http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=preview

推荐答案

一个可能的问题,即当 ngIf 被放置在模板的根元素。结果
ngIf 删除节点,并将评论在它的地方。然后,看守的前pression并添加/删除实际的HTML元素是必要的。这个问题似乎是,如果它被放置在模板的根元素,然后一个单一的评论是从整个模板(即使只是暂时的),它被忽略左(我不知道这是否是浏览器的特定行为),从而产生一个空的模板

One possible problem arises when the ngIf is placed on the root element of the template.
ngIf removes the node and places a comment in it's place. Then it watches over the expression and adds/removes the actual HTML element as necessary. The problem seems to be that if it is placed on the root element of the template, then a single comment is what is left from the whole template (even if only temporarily), which gets ignored (I am not sure if this is browser-specific behaviour), resulting in an empty template.

如果的确是这样,你可以在换你的 ngIf ED元素&LT; D​​IV&GT;

If that is indeed the case, you could wrap your ngIfed element in a <div>:

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


又见这个 短演示


See, also, this short demo.

另一个可能的错误与空白模板的结局,因为它不是在 $ templateCache present。即如果你不把它放入 $ templateCache exlicitly,那么下面的code将返回未定义(结果到一个空的元素):

Another possible error is ending with a blank template, because it is not present in the $templateCache. I.e. if you don't put it into the $templateCache exlicitly, then the following code will return undefined (resulting into an empty element):

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

这篇关于测试NG-如果使用$编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆