Accessing the same variable in a directive and controller in AngularJS

A few days ago, I was working with this type of structure in AngularJS:

<div class='container' ng-controller='formController'>
  ...some stuff...
  <content-tag-buttons></content-tag-buttons>
</div>

I had a directive, contentTagButtons inside of an Angular controller, which was pretty basic.  I needed to be able to assign a value to a variable in the contentTagButtons directive, but still have access to it in formController. This is where directive scope comes in handy.

In my directive:

var app = angular.module("myApp", []);

app.directive("contentTagButtons", function() {
  return {
    restrict: "E",
    scope: false, // the important part
    link: function($scope, element, attrs) {
      $scope.someSharedVar = "bikes are cool";
    }
  }
})

 

For my purposes when I set the scope attribute to false, the directive uses its parent scope. This means that $scope.someSharedVar my contentTagButtons directive  would be the same as $scope.someSharedVar in my formController controller.

Shidhin explains directive scoping in more detail in his post here.

Related Posts with Thumbnails

Leave a Reply

Your email address will not be published. Required fields are marked *