2014-03-26 21 views
1

我已经在一个元素上声明了两个指令:一个请求隔离范围,另一个请求继承范围。这里是:在同一元素上请求隔离作用域和继承作用域的两个指令

守则

angular.module("myApp", []) 
.directive("myDirective", function() { 
    return { 
     restrict: "A", 
     scope: { 
      users: "=" 
     }, 
     templateUrl: "users-info.html", 
     link: function(scope) { 
      scope.title = "From My Directive"; 
     } 
    } 
}) 
.directive("otherDirective", function() { 
    return { 
     restrict: "A", 
     scope: true, 
     link: function(scope) { 
      scope.title = "From Other Directive"; 
     } 
    }; 
}) 
.controller("AppController", function($scope) { 
    $scope.users = [ 
     {name: "Anup Vasudeva", username: "anup_vasudeva"}, 
     {name: "Ajay Sharma", username: "ajay_sharma"}, 
     {name: "Vinay Kumar", username: "vinay_kumar"} 
    ]; 
    $scope.title = "Users Information"; 
}); 

和HTML

<div my-directive other-directive>{{title}}</div> 

但AngularJS抛出错误提的网址:

http://docs.angularjs.org/error/$compile/multidir 

但在描述的错误,我没有看到它指出请求隔离和继承范围的多个指令是不允许的。

**编辑** 这似乎很奇怪,当我使用角v1.2.0-rc.2时,上述情况正常工作。即使它请求共享范围,otherDirective也会获得一个隔离范围。但是这种情况在最新版本中不起作用。

回答

2

,因为两者的指令都要求一个孤立的范围你得到一个错误。

app.directive("otherDirective", function() { 
    return { 
     restrict: "A", 
     scope: false, 
     link: function(scope) { 
      scope.title = "From Other Directive"; 
     } 
    }; 
}); 

here's a fiddle

其实,你可以省略了同样的效果范围的属性,以及:

要解决这个问题,作用域选项上的指示,你想上没有孤立的范围设置为false 。

+0

Thanks @Nick。 otherDirective是否有可能拥有继承范围?我希望otherDirective能够访问“用户”模型 –

+0

它具有继承范围。看到我更新的小提琴:[http://jsfiddle.net/24Pyg/1/](http://jsfiddle.net/24Pyg/1/)。其他Directive范围的标题来自其父控制器。从我看到的 – Nick

+0

中,其他指令具有共享范围,而不是继承范围。纠正我,如果我错了。我关心的是为什么otherDirective在请求继承范围时出现错误。 –

0

AngularJS每个元素只允许一个独立的作用域。如果任何一个,如果你做

scope: true 

scope: {/* something */} 

在相同的元素两个指令中,这只是意味着你在相同的元素,要求两个独立的范围。

scope: false 

尝试在otherDirective

+0

谢谢@Ashesh:我相信,即使otherDirective正在请求继承范围,隔离范围将在myDirective和otherDirective之间共享。我最担心的是,至少AngularJS不应该抛出任何错误 –

+0

@AnupVasudeva它只会抛出一个错误,因为单个元素上的隔离范围并不会让生活变得简单。 :-)我觉得这是完全合理的。在概念上,一个元素最多对应于Angular术语中的一个独立范围。假设在两个或多个作用域中有两个具有相同名称的变量,并且在这种情况下,您在同一元素上有两个作用域。你认为我们会如何解决这种情况? – Ashesh

+0

我已编辑帖子。请看一看。 –

相关问题