SBay
SBay

Reputation: 23

AngularJS: How to inherit the scope the directive locates in, and get attributes value same time

Could anybody help with this? Is there a way to access the scope the directive located in (e.g. a controller's scope) while I still can access the attributes' value.

here is my directive code

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
    }
   };
}]);

and here is the HTML:

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

In the directive I cannot access the scope['controllerScopeVariable']. How can I do that?

Upvotes: 0

Views: 169

Answers (1)

Sven Sch&#252;rmann
Sven Sch&#252;rmann

Reputation: 612

You have to define the variable controllerScopeVariable also in the scope property of your directive.

For example:

    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'];
    }
   };
}]);

Keep in mind there will be three ways to define local scope properties you can pass:

  • @ Used to pass a string value into the directive
  • = Used to create a two-way binding to an object that is passed into the directive
  • & Allows an external function to be passed into the directive and invoked

Upvotes: 1

Related Questions