Jordan McDonald Jordan McDonald - 3 months ago 24
Javascript Question

scope.$parent.messageContent= value not updating the parent scope from directive

I could have sworn I had this working earlier but now I just cannot get the parent scope to update and display on the page.

In the parent I have some a simple scope I want to update from the directive.
In the parent controller I set it like this.

$scope.messageContent = 'The initial content';

In the parent view I have it displayed


I made it very simple for a test and here is the directive. In my link function in the directive I have this code:

link: function (scope, element, attrs) {
scope.$parent.messageContent = 'New content';

It simply will not update the parent. What am I missing here?



You probably have an ng-if or another Angular directive (ng-repeat, ng-switch, ...) that creates a new scope, so you have to go up the chain with more $parent declarations.

Better option is to use an object.


$scope.message = {content: 'some content'};


link: function (scope, element, attrs) {
    scope.message.content = 'New content';

Using an object instead of a primitive to solve the resolution problem works due to JavaScript's prototypal inheritance.
For a detailed answer - see this: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?