测试ng-if使用$ compile

Dan*_*Dan 11 angularjs

我试图在我的一个模板中测试ng-if,通过针对预定义的范围编译视图并运行$ scope.$ digest.

无论我的条件是真实的还是假的,我发现编译后的模板都是一样的.我希望编译的html在falsy时删除ng-if dom元素.

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
});
Run Code Online (Sandbox Code Playgroud)

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

gka*_*pak 19

ngIf放置在模板的根元素上时会出现一个可能的问题.
ngIf删除节点并在其中放置注释.然后它监视表达式并根据需要添加/删除实际的HTML元素.问题似乎是如果将它放在模板的根元素上,那么单个注释就是整个模板留下的内容(即使只是暂时的),这会被忽略(我不确定这是否是浏览器 - 特定行为),导致空模板.

如果确实如此,您可以将ngIfed元素包装在<div>:

<div><h1 ng-if="test">Hello, world !</h1></div>
Run Code Online (Sandbox Code Playgroud)

另见这个简短的演示.


另一个可能的错误是以空白模板结束,因为它不存在于空白模板中$templateCache.即如果你没有把它放入显$templateCache式,那么下面的代码将返回undefined(导致一个空元素):

$templateCache.get('myTemplate.tpl.html')
Run Code Online (Sandbox Code Playgroud)