2015-10-06 150 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與您的子範圍共享。 –