Angularjs 为什么$rootScope.$new不允许模板进入指令?
我正在使用Karma和Mocha构建单元测试。测试我的指令,并使用html2js(它将htmls转换为$templateCache中的缓存字符串)。 有趣的是,在测试中使用$rootScope.$new()时,模板html不会进入指令。代码如下:Angularjs 为什么$rootScope.$new不允许模板进入指令?,angularjs,angularjs-directive,mocha.js,karma-runner,Angularjs,Angularjs Directive,Mocha.js,Karma Runner,我正在使用Karma和Mocha构建单元测试。测试我的指令,并使用html2js(它将htmls转换为$templateCache中的缓存字符串)。 有趣的是,在测试中使用$rootScope.$new()时,模板html不会进入指令。代码如下: it('should show a thumb name', function() { inject(function($compile, $rootScope,$controller) { var scope = $rootScope;//
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
}));
it('应显示拇指名称',函数(){
注入(函数($compile、$rootScope、$controller){
var scope=$rootScope;/.$new()($new不工作。为什么?)
var linkFn=$compile(“”);
var元素=linkFn(范围);
scope.$digest();//根据$digest
(.$rootScope.scope)的文档,这将仅处理当前作用域及其子项的观察者等
这对我来说意味着,当你设置scope=$rootScope
然后$digest
时,你将在$rootScope
上处理观察者等,我认为这也是承诺解决的地方,释放你的模板
并调用$digest
,我希望$rootScope
中应该发生的任何事情都不会发生
那么,如果您将
scope.$digest()
更改为$rootScope.$digest()
或scope.$apply(),这是否有效
?你需要提供你所有的代码。元素在测试的其他地方定义了吗?thumb
是一个指令吗?嗯……很有趣。你可能是对的。我必须检查一下。谢谢!在写下答案后,我不确定$apply
,所以我检查了代码,以确保它调用$rootScope
上的摘要-是的,ra而不是电流。我为此挣扎了几个小时。这个答案证实了一些怀疑。