Jordan McDonald Jordan McDonald - 25 days ago 13
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

{{$scope.messageContent}}


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?

Thanks

Answer

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.

Controller:

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

Directive

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?

Comments