2015-10-06 147 views
1

我有一个指令,如下所示“范围”的指导链接功能是根范围,而不是指令范围

.directive('ticketingChat', function() { 
    return { 
     restrict: 'E', 
     templateUrl: '/Reply/ReplyScreen', //cshtml from MVC page 
     controller: 'TicketingChatController', 
     link: function (scope, el, attr) { 
      scope.writingTo = "Hey there!"; 
     } 
    } 
}) 

我认为这将创造它自己的范围,“范围”可以让我访问它。

相反,NG-检查表明我说:

enter image description here

“范围” 其实,根范围内。我如何强制指令创建它自己的子范围? 如何从链接功能访问该范围?

+0

它取决于您如何在html中使用您的指令,它使用了当前作用域,也可能不是_ $ rootScope_,而是** $ rootScope的子**,其ID = 002 – Grundy

+0

也如果您看到doc:为了创建自己的作用域,你应该在返回的对象中使用'scope:{}' – Grundy

回答

1

在指令定义对象中设置scope: true会使AngularJS创建一个继承的子作用域。将scope设置为对象将创建一个独立的子范围。

例如:

.directive('ticketingChat', function() { 
    return { 
     restrict: 'E', 
     templateUrl: '/Reply/ReplyScreen', 
     controller: 'TicketingChatController', 
     scope: true, 
     link: function (scope, el, attr) { 
      scope.writingTo = "Hey there!"; // This will be set on the child scope because we have scope: true. 
     } 
    } 
}) 

the docs,了解有关scope特性的详细信息。

+0

如果我需要执行'scope.ticket.Id = attr ['ticketid'];' – David

+0

如果'scope:true',那么子作用域将源范围作为其父范围,因此'scope.ticket'将解析为父范围的'ticket'成员(如果它存在于父项中)。 –

+0

'scope:{ticketId:“= ticketid”},'如果您只希望将此ID与您的子范围共享。 –