Javascript Angularjs templateUrl与模板范围问题
我在路上遇到了一种奇怪的行为。 创建指令时,如果使用Javascript Angularjs templateUrl与模板范围问题,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我在路上遇到了一种奇怪的行为。 创建指令时,如果使用 mod.directive('test', [function(){ return { restrict: 'E', templateUrl: '/test/test.html', transclude: true, controller: ['$scope',function($scope){ //$scope equals con
mod.directive('test', [function(){
return {
restrict: 'E',
templateUrl: '/test/test.html',
transclude: true,
controller: ['$scope',function($scope){
//$scope equals containing scope of directive. why???
}]
};
}]);
$scope与包含指令作用域的作用域相同(不是继承的)
但是如果我把指令创建为
mod.directive('test', [function(){
return {
restrict: 'E',
template: '<div><div ng-transclude /></div>',
transclude: true,
controller: ['$scope',function($scope){
//$scope is new. inherited from container scope
}]
};
}]);
mod.directive('test',[function(){
返回{
限制:'E',
模板:“”,
是的,
控制器:['$scope',函数($scope){
//$scope是新的。从容器作用域继承
}]
};
}]);
唯一的区别是模板和模板URL。“templateUrl”一个使用父作用域,但“template”一个创建一个新作用域。我不明白为什么。这可能是一只角虫吗
已经谢谢你了
编辑:我使用的是Angular 1.3.0-beta.7
大编辑:我正在对@estus提到的同一元素使用另一个指令
<test other-directive></test>
其他指令定义为scope:true。但当与测试指令上的templateUrl一起使用时,它不会创建新的作用域
编辑:示例plnkr(模板URL)
plnkr->(模板)这会让人困惑,但对于异步加载模板的指令(通过templateUrl
):
由于模板加载是异步的,编译器将挂起
编译该元素上的指令,以便稍后在模板
已经解决了。与此同时,它将继续进行编译和编辑
链接同级元素和父元素,就像此元素没有
包含任何指令
要解决此问题,请首先使用优先级编译具有新范围的指令:
app.directive('directiveOne', function () {
return {
restrict: 'E',
templateUrl: 'directive-template.html',
transclude: true,
controller: ['$scope', function($scope){
...
}]
};
});
app.directive('directiveTwo', function () {
return {
priority: 100,
scope: true
};
});
是的,在同一个元素上有另一个指令。请参见编辑的问题,并提供答案。是什么让你认为templateUrl的指令没有新的作用域?我明天会在办公室发布一个有效的plunkr。我的代码现在不在我身边。我在问题中添加了plnkr。是的,缓存的模板在这里不是说明性的,因为当指令第一次被编译时,它的模板将被异步加载。我已经更新了答案以匹配问题。