Pharylon
Pharylon

Reputation: 9916

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.

Upvotes: 0

Views: 668

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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

Upvotes: 4

Related Questions