[AngularJS] Updating parent scope from a directive

Here’s the scenario.

I had a settings page for opening hours for a restaurant, which you set opening hours from Monday – Sunday.

I implemented a button on Monday, that allows you to use the same settings for all other days.

I bind this button to a directive, to capture the values of Monday, and then loop through Tues-Sun, clearing their select boxes, and populating them with the select boxes according to what Monday is set. (The reason why I’m not directly changing their ng-model value is because we can set multiple opening hours per day, which is done via an array in ng-model)

So far, the values get populated on screen beautifully. Upon clicking Save, I realised something:

THE VALUES FOR TUES – SUN ARE EMPTY

The reason was because, i was setting the values in the directive via scope.tue_start, scope.tue_end, etc.

That meant I was setting the hours to these variables for the scope of the directive, NOT the parent/page.

So the question came down to:

How do I update the parent scope from within a directive?

After alot of headaches and searching, I finally found the syntax.

from within a directive, to access the parent scope, use

scope.$parent.xxx

Some other people suggested defining a method in the parent scope to update the values, ie. updateOpeningHours(day)

And then calling that method from the directive scope. I haven’t given it a try, although I see it as a modular approach, for now, I’m quite happy with this simpler syntax.

 

 

No Comments

Cancel