2013-07-16 38 views
3

例如,我有指令AngularJS:rootScope在指令作用域

App.directive('module', function($compile) 
{ 
    return { 

     replace  : true,   
     restrict : 'E', 
     link: function(scope, iElement, iAttrs) 
     { 
      scope.localName = '1'; 
     }, 

     template : '<div> {{ name }} - {{ localName }}</div>', 
    }  
}); 

在應用程序運行的功能:

App.run(function($rootScope, $location) 
{ 
    $rootScope.name = "test"; 
} 

所以在這樣指令的範圍將是相同的所有指令,但這個範圍將有權訪問$ rootScope

<module></module> 
<module></module> 

http://i.stack.imgur.com/QF8wM.png

但是,如果我將一個孤立的範圍:

App.directive('module', function() 
{ 
    return { 

     replace  : true,   
     restrict : 'E', 
     link: function(scope, iElement, iAttrs) 
     { 
      scope.localName = '1'; 
     }, 

     template : '<div> {{ name }} - {{ localName }}</div>', 
      scope : {} 
    }  
}); 

作用域會有所不同,但他們將有機會獲得$ rootScope

http://i.stack.imgur.com/XITHr.png

所以我需要每一個指令的範圍隔離,但我需要這個範圍必須$ rootScope訪問。

你能幫助我嗎?

回答

4

scope: true

不是分離的,未共享,但每指令實例的新prototipically繼承範圍。

http://jsfiddle.net/4LAjf/1

您可以登錄範圍的ID與console.log(scope.$id)。與scope: {},你會得到,例如,003和004.與scope: false(或沒有),範圍是共享的,例如,都有002. 與scope:true他們有不同的id,但可以讀取$rootScope

在現場示例中,您可以在本地變量localName中看到範圍ID。我將虛擬指令命名爲mydir而不是module。它只是看起來怪異的命名模塊一個指令。

More about AngularJS scopes

+0

謝謝。有用的信息 – tuchk4

+0

拯救我的生命不知道這件事可能會導致這麼多問題 –

相關問題