我正在使用 Karma 和 Mocha 构建单元测试。测试我的指令,并使用 html2js(它将 html 转换为 $templateCache 中的缓存字符串)。
有趣的是,在我的测试中使用 $rootScope.$new() 时,模板 html 不会进入指令。这是代码:
it('should show a thumb name', function() {
inject(function($compile, $rootScope,$controller) {
var scope = $rootScope;//.$new() ($new not working. Why?)
var linkFn = $compile('<thumb></thumb>');
var element = linkFn(scope);
scope.$digest(); // <== needed so that $templateCache will bring the html
// (that html2js put in it)
console.log(element.html());// correctly returns thumb's directive templateUrl content
}));
...
然而 , 如果我使用 scope = $rootScope.$new(), element.html() 将返回一个空字符串
有任何想法吗?
非常感谢
利奥尔
最佳答案
根据 $digest
的文档( http://docs.angularjs.org/api/ng .$rootScope.Scope),这只会处理 的观察者等当前 范围及其子项。
这向我表明,当您设置 scope = $rootScope
时然后 $digest
您将在 $rootScope
上处理观察者等,我认为这也是 promise 将得到解决的地方,发布您的模板。当您这样做时scope = $rootScope.$new()
并调用 $digest
在这一点上,我希望从 $rootScope
发生任何事情。不会发生。
那么,如果您更改 scope.$digest()
,这是否有效?至 $rootScope.$digest()
或 scope.$apply()
?
关于angularjs - 为什么 $rootScope.$new 不让模板进入指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201228/