Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the parent scope within a directive link

Tags:

angularjs

So on the angular documentation website, you can define Tobias and Jeff

angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.name = 'Tobias';
}])
.directive('myDialog', function() {
  return {
   restrict: 'E',
    transclude: true,
    scope: {},
    templateUrl: 'my-dialog.html',
    link: function (scope, element) {
      scope.name = 'Jeff';
    }
  };
});

If you do The name is {{name}} it'll say

The name is Tobias

I'm trying to access Tobias in the link function. From inside the link function, how would I get the $scope.name value equal to Tobias?

like image 839
UX Guy Avatar asked Jan 05 '15 21:01

UX Guy


1 Answers

Since the scope is isolated scope: {}, directive creates a new child scope. In this case the only way to directly access parent scope property is to use scope $parent, reference to parent scope object. For example:

link: function(scope, element) {
    scope.name = 'Jeff';
    scope.parentName = scope.$parent.name; // Tobias
}

However this is not ideal. This is why you may want to consider more flexible approach:

<my-dialog name="name"></my-dialog>

and define a scope configuration as:

scope: {
    parentName: '=name'
}
like image 140
dfsq Avatar answered Nov 02 '22 06:11

dfsq