Wednesday, 15 April 2015

angularjs - What's the best way for an angular controller to alter an ancestor HTML element? -



angularjs - What's the best way for an angular controller to alter an ancestor HTML element? -

i have angular controller lives in portion of page application needs access html element lives above it.

the best way imagine problem have embedded video wants request made total view-port:

<html ng-app="videoapp"> <body> <div> other stuff doesn't relate video player... </div> <div ng-controller="videoctrl"> ... stuff relating video controller </div> </body> </html>

the exact problem videoctrl needs able add together class body class such can switch page layout beingness full-page , dominated video.

desired outcome, status of video app adds "full-page" class body tag:

<body ng-class="video.fullpage ? 'full-page', : ''"> what's right way video add together class ancestor tag?

under normal circumstances element want manipulate lies within controller that's doing manipulation can bind elements variables in scope:

<body> <!-- videoctrl scope not available <body> --> <div ng-controller="videoctrl"> <div ng-class="video.fullpage ? 'fullpage' : ''"></div> </div> </body>

however body tag not contained within scope of video controller , has no access variables in scope can't bind them.

we reach out straight , alter class on body using dom manipulation that's not angular. right pattern video controller alter class of body tag?

to meet similar requirement, used angular events. controller, $broadcast event on $rootscope. have sort of screen layout controller handle event , toggle possible screen configurations.

so:

child controller:

$rootscope.$broadcast('layout-action', { configuration: 'video' });

layout controller:

$scope.$on('layout-action', function(event, args) { if (args.configuration == 'video') { $scope.showvideo = true; } });

html:

<body ng-class="{'full-page': showvideo}">

*note: tie kid functionality part of layout. however, perhaps seek generalize video layout. example, maybe want full screen mode instead.

angularjs

No comments:

Post a Comment