Search code examples
angularjsangularjs-directivecontrollerdirectiveisolate-scope

Accessing Controller Scope from child Directive in Angular


I want to access a controller scope without using $parent. From everything I read, I thought I could just pass it into the isolate scope as follows:

  <body ng-app="app" ng-controller="myController">
    <h1>
      {{message}}
    </h1>
    <mydir></mydir>

angular.module('app', [])

.controller('myController', function($scope){
  $scope.message = "Hello World";
})

.directive('mydir', function(){
  return {
    restrict: "E",
    scope: {
      message: "=",
    },
    controller: function($scope){
      $scope.goodbye = function(){
        $scope.message = "Goodbye World";
      }
    },
    template: "<button ng-click='goodbye()'>Say Goodbye</button>"
  }
})

However, I can't get the directive to update the scope's message property. Plnkr link.


Solution

  • Since the isolated scope value can passed using attribute, then you need to have message attribute on directive element which will have the scope variable name.

    <mydir message="message"></mydir>
    

    Demo Plunker