javascript - Angularjs templateUrl 与模板范围问题

标签 javascript angularjs angularjs-directive angularjs-scope

我在 Angular 上遇到了一个奇怪的行为。 在创建指令时,如果我使用

 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 与 templateUrl。 “templateUrl”一个使用父范围,而“template”一个创建一个新范围。我不明白为什么。这可能是一个 Angular 错误吗?

已经谢谢了

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

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

<test other-directive></test>

other-directive 被定义为 scope:true。但在测试指令上与 templateUrl 一起使用时,它不会创建新范围。

编辑:示例 plnkr http://plnkr.co/edit/Kghah1rvwFE6TSw85Cog?p=preview (模板网址)

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

最佳答案

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

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.

为了解决这个问题,首先使用 priority 来编译具有新作用域的指令:

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

关于javascript - Angularjs templateUrl 与模板范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097593/

相关文章:

javascript - 当使用angularjs,ngInit加载 View 时初始化范围值的正确方法?

javascript - DatePicker Angular

javascript - 使用 jquery 修改文本区域的撤消/重做行为

javascript - 出于什么目的 'no-use-before-define' 警告已声明的函数?

javascript - 无法从指令中的隔离范围广播 - 将指令范围设置为 false 的负面影响?

javascript - 在 ngOption <select> 中使用 unicode 符号

javascript - AngularJs:从另一个指令内的指令调用 Controller 方法

angularjs - 如何使用 RequireJS AngularJS 和 Google Visualization API

javascript - Microsoft JScript 运行时错误 : 'Array' is undefined error in IE 9 while using fancy box

php - 如何从字符串输出中删除回车符?