0

任何人都可以幫忙嗎?有沒有辦法訪問位於指令中的指令(例如控制器的作用域),而我仍然可以訪問屬性的值。AngularJS:如何繼承指令所在的範圍,並獲得同一時間的屬性值

這裏是我的指令代碼

app.controller("someCtr", function($scope){ 
    $scope.controllerScopeVariable = "Lorem"; 
}); 
app.directive('myDirective', [function() { 
return { 
    restrict: 'A', 
    scope: { 
     directiveAttributeValue: "=" 
    }, 
    link: function (scope, element, attrs) { 
     var bar = scope['directiveAttributeValue']; 
     var foo = scope['controllerScopeVariable']; //I need to access this 
    } 
    }; 
}]); 

這裏是HTML:

<div ng-controller="someCtr"> 
     <div myDirective directiveAttributeValue="{{blabla}}"> 
     </div> 
    </div> 

在指令我無法訪問範圍[ 'controllerScopeVariable']。我怎樣才能做到這一點?

+0

隔離範圍('scope。$ new(true)')不_從__繼承父範圍。您可以查看其他作用域選項,例如'scope:true',您將獲得其父項的繼承子範圍。你總是可以使用'attrs'來讀取屬性值,你可以做'attrs ['directiveAttributeValue']'或'scope。$ eval(attrs ['directiveAttributeValue'])'如果你從父範圍繼承,不需要它。 – PSL 2014-10-07 15:44:23

+0

您的拼寫錯誤屬性必須是'directive-attribute-value'才能在您的案例中以'attrs ['directiveAttributeValue']'或'scope.directiveAttributeValue'的形式訪問它 – PSL 2014-10-07 15:49:39

+0

您也有很多錯誤。 .. http://plnkr.co/edit/zwbgdY?p=preview – PSL 2014-10-07 15:54:56

回答

1

您必須在您的指令的scope屬性中定義變量controllerScopeVariable

例如:

app.controller("someCtr", function($scope){ 
    $scope.controllerScopeVariable = "Lorem"; 
}); 
app.directive('myDirective', [function() { 
return { 
    restrict: 'A', 
    scope: { 
     directiveAttributeValue: "=", 
     controllerScopeVariable: "&" 
    }, 
    link: function (scope, element, attrs) { 
     var bar = scope['directiveAttributeValue']; 
     var foo = scope['controllerScopeVariable']; 
    } 
    }; 
}]); 

記住將有三種方式來定義局部範圍的屬性可以通過:

  • @用於將一個字符串值傳遞到指令
  • =用於創建雙向綁定到傳入指令的對象
  • &允許將外部函數傳入該指令並被調用
相關問題