我试图通过针对预定义范围编译视图并运行 $scope.$digest 来测试我的模板之一中的 ng-if。
我发现无论我的条件是真还是假,编译的模板都是一样的。我希望编译后的 html 在 false 时删除 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
});
这是一个尝试展示正在发生的事情的 plunker(不知道如何在 plunker 中测试,所以我在控制器中完成了它)http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=preview http://plnkr.co/edit/Kjg8ZRzKtIlhwDWgB01R?p=preview
当ngIf
放置在模板的根元素上。
ngIf
删除节点并在其位置添加注释。然后它监视表达式并根据需要添加/删除实际的 HTML 元素。问题似乎是,如果它被放置在模板的根元素上,那么单个注释就是整个模板留下的内容(即使只是暂时的),它会被忽略(我不确定这是否是浏览器-特定行为),导致模板为空。
如果确实如此,您可以将您的ngIf
a 中的 ed 元素<div>
:
<div><h1 ng-if="test">Hello, world !</h1></div>
另请参阅此简短的演示 http://jsfiddle.net/ExpertSystem/ScLM2/.
另一个可能的错误是以空白模板结尾,因为它不存在于$templateCache
。 IE。如果你不把它放入$templateCache
明确地,那么以下代码将返回undefined
(导致一个空元素):
$templateCache.get('myTemplate.tpl.html')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)