编程语言
首页 > 编程语言> > javascript-Angularjs templateUrl与模板作用域问题

javascript-Angularjs templateUrl与模板作用域问题

作者:互联网

我在角度上遇到了奇怪的行为.
当我创建指令时

 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
         }]
     };
 }]);

唯一的区别是template vs templateUrl. “ templateUrl”使用父范围,但“ template”创建一个新范围.我不明白为什么.这可能是一个有角度的错误吗?

已经感谢

编辑:我正在使用Angular 1.3.0-beta.7

大编辑:我在与@estus提到的相同元素上使用另一个指令.

<test other-directive></test>

other-directive定义为scope:true.但与test指令上的templateUrl一起使用时,它不会创建新的作用域.

编辑:示例plnkr http://plnkr.co/edit/Kghah1rvwFE6TSw85Cog?p=preview(templateUrl)

plnkr-> http://plnkr.co/edit/Axiye1ksBMR8dp9ND8tL?p=preview(模板)

解决方法:

这很令人困惑,但是对于带有异步加载的模板(通过templateUrl)的指令,其值为expected behaviour

Because template loading is asynchronous the compiler will suspend
compilation of directives on that element for later when the template
has been resolved. In the meantime it will continue to compile and
link sibling and parent elements as though this element had not
contained any directives.

要解决此问题,请首先使用优先级以新作用域编译指令:

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
    };
});

标签:angularjs,angularjs-directive,angularjs-scope,javascript
来源: https://codeday.me/bug/20191119/2039323.html