Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core/reactShims): Add angularJS template/controller adapter (#4730)
* feat(core/reactShims): Add angularJS template/controller adapter
- Loading branch information
1 parent
5e48a3c
commit b183954
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
app/scripts/modules/core/src/reactShims/AngularJSAdapter.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import * as React from 'react'; | ||
import * as angular from 'angular'; | ||
import { IScope } from 'angular'; | ||
import { $compile, $controller } from 'ngimport'; | ||
|
||
export interface IRenderAngularJSProps { | ||
template: string; | ||
controller: string; | ||
locals?: { [key: string]: any }; | ||
} | ||
|
||
export class AngularJSAdapter extends React.Component<IRenderAngularJSProps> { | ||
public static defaultProps: Partial<IRenderAngularJSProps> = { locals: {} }; | ||
private $scope: IScope; | ||
|
||
constructor(props: any) { | ||
super(props); | ||
} | ||
|
||
public componentWillReceiveProps(nextProps: IRenderAngularJSProps) { | ||
this.$scope.props = nextProps; | ||
} | ||
|
||
private refCallback(ref: Element) { | ||
if (!ref) { | ||
return; | ||
} | ||
|
||
const { template, controller, locals } = this.props; | ||
const $element = angular.element(ref); | ||
|
||
const parentScope = $element.scope(); | ||
const $scope = this.$scope = parentScope.$new(); | ||
$scope.props = this.props; | ||
|
||
$element.html(template); | ||
$compile(ref)($scope); | ||
|
||
if (controller) { | ||
const controllerInstance = $controller(controller, { $scope, $element, ...locals }); | ||
$element.data('$ngControllerController', controllerInstance); | ||
} | ||
} | ||
|
||
public componentWillUnmount() { | ||
this.$scope.$destroy(); | ||
} | ||
|
||
public render() { | ||
return <div ref={(ref) => this.refCallback(ref)} /> | ||
} | ||
} |