Ryan.lay
Ryan.lay

Reputation: 1761

Angularjs: How to access controller scope in directive?

I have 2 elements like so:

<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
   <div directive></div>
</div>

And a directive like so:

app.directive ('directive', [
   ...
   controller: [
        '$scope',
        function ($scope) {
          $scope.accept = function () {
            $scope.showDiv = false;
          };
        }
      ],
   ....
]

I tried to use $scope.showDiv within the directive to toggle the controller but it didn't work. How do I access the controller's scope within the directive?

console.log($scope) in the directive shows $scope.showDiv === false though $scope.showDiv === true in the controller.

Upvotes: 0

Views: 220

Answers (2)

Ryan.lay
Ryan.lay

Reputation: 1761

$scope.showDiv = true

is a primitive value and is not inherited by the directive's scope. Assigning the value to an object allows the directive's scope to inherit the object, and any changes in the directive scope will be passed back up to the parent scope.

//controller
//change primitive to object
$scope.showDiv = {status: true};

//template
//directive names in HTML are usually in kebab case but i'm keeping it obvious for now.
//Pass showDiv object to directive
<div ng-show="showDiv.status">
    <div directive showDiv="showDiv"></div>
</div>

//directive
app.directive ('directive', [
  ...
  return {
    scope : {
       //bind directive scope to parent
       showDiv: '=showDiv'
    }
    controller: [
        '$scope',
        function ($scope) {
          $scope.foo = function () {
            //Changing object in directive will also update parent scope. 
            $scope.showDiv.status = false;
          };
        }
      ],
   ....
]

//controller
//after $scope.foo executed in directive
console.log(showDiv) === {status: false}

Upvotes: 0

Knut Holm
Knut Holm

Reputation: 4162

You can simply achieve this if you use controllerAs syntax.

HTML

<div ng-hide="showDiv"></div>
<div ng-show="showDiv">
   <div dir-show-div is-shown="showDiv"></div>
</div>

Directive

angular
   .module('app')
   .directive('dirShowDiv', dirShowDiv);

function dirShowDiv() {
   var directive = {};

   directive.scope = {
      isShown: '='
   };
   directive.controller = 'DirController';
   directive.controllerAs = 'vm';

   return directive;
}

Directive Controller

angular
    .module('app')
    .controller('DirController', DirController);

function DirController() {
   var self = this;

   self.accept = accept;

   function accept() {
      self.isShown = false;
   }
}

Upvotes: 1

Related Questions