1

我想設置隔離範圍內的變量,但我不能訪問變量,我在隔離範圍內的鏈接功能中設置,也我可以訪問控制器的變量。如何設置範圍變量在隔離範圍從鏈接功能

app.directive('myDir', function($timeout) { 
    return { 
     restrict: 'A', 
     scope: { 
      'propVar': '=' 
     }, 
     link: function(scope, elem) { 
      console.log(elem) 
      scope.linkVar = 'It works!' 
      console.log(scope); 
     }, 
    } 
}) 

我創建plunker來說明我的意思:http://plnkr.co/edit/lUBvIkF4fKXkEgujJpuU?p=preview

回答

3

它工作的一切理所應當的。

1)如果你定義了'propVar' : '='這意味着你的指令元素有一個屬性prop-var。不是這種情況。如果您想使用prop屬性,則必須以這種方式定義您的隔離範圍:'propVar' : '=prop'

2)您的指令的子元素綁定到控制器範圍而不是指令範圍。如果您想將子元素是你的指令的一部分,您可以在您的指導使用模板:

app.directive('myDir', function() { 
    return { 
     restrict: 'A', 
     template: '<div><p>linkVar: {{ linkVar }}</p><p>propVar: {{ propVar }}</p><p>foo: {{ foo }}</p><button ng-click="foo=\'directive sucks\'">press me</button></div>', 
     scope: { 
      propVar: '=prop' 
     }, 
     link: function(scope, elem) { 
      console.log(elem) 
      scope.linkVar = 'It works!' 
      console.log(scope); 
     }, 
    } 
}) 

看到修改後的PLUNKR:http://plnkr.co/edit/MHXXkmPdtfAUqtre4Fbg?p=preview

+0

是的,但問題是,我不希望使用模板。我想在我的div的innerHTML中的東西的隔離範圍。可能嗎? – syabro

+2

嗯。它使用一個小補丁:template:function(tElement,tAttrs){return tElement [0] .innerHTML; } 但謝謝你的回答;) – syabro

+0

@syabro很好的解決方案! :) – michael