1

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

George Kagan
  • 5,913
  • 8
  • 46
  • 50
Jordan McDonald
  • 1,101
  • 3
  • 14
  • 24
  • You can try emit and broadcast http://stackoverflow.com/questions/29999407/send-an-event-using-emit-from-directive-to-controller – Amey Kamat Nov 09 '16 at 17:11

1 Answers1

0

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?

Community
  • 1
  • 1
George Kagan
  • 5,913
  • 8
  • 46
  • 50