Growler Growler - 5 months ago 22
AngularJS Question

Update parent controller value from child angular function

I'm trying to change a scope value in a parent controller from a child directive.

I've added

=
for two-way binding such that when I click on a the directive's
<tr>
, it will fire
openDetail
, which will update
scope.page
, which has been two-way bound.

Yet it's not updating the controller's
page
value.

Controller HTML:

TEST : {{page}} //Not changed

<questions-list></questions-list>


Controller:

$scope.page = 'Not changed';


Directive HTML:

<tr ng-repeat="q in questions" ng-click="openDetail( q.id )">


"Questions List" Directive:

scope: {
page : '='
},
...

scope.openDetail = function (id) {
scope.page = 'question_detail';
};





In other examples, the
ng-click
handlers are always bound on the Controller. In my case, I need to fire an event from the directive, change directive value, and have it update the controller.

Answer

You should pass the parent scope's property to bind to via directive's element attribute:

<questions-list page="page"></questions-list>

Here the demo.

Comments