Skip to content

Instantly share code, notes, and snippets.

@wallrat
Forked from anonymous/jsbin.ENILAqEY.coffee
Last active January 2, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallrat/8318710 to your computer and use it in GitHub Desktop.
Save wallrat/8318710 to your computer and use it in GitHub Desktop.
Experimental glue code for using React components in AngularJS apps.
reactModule = angular.module 'react',[]
#
# Usage <div react-attach={{React class}} react-prop-{{React prop}}={{angular scope expression}}* />
#
reactModule.directive 'reactAttach', ->
return {
restrict: 'A'
link: (scope,element,attrs) ->
# get React component construnctor fn
reactClass = window[attrs.reactAttach]
# initial props
props = $scope: scope
for attr,val of attrs
if attr.indexOf('reactProp') is 0
a = attr[9].toLowerCase() + attr.substr(10)
props[a] = scope.$eval val
# attach React component to DOM
reactComponent = React.renderComponent reactClass(props), element[0]
# add scope watches
for attr,val of attrs
do (attr,val) ->
if attr.indexOf('reactProp') is 0
a = attr[9].toLowerCase() + attr.substr(10)
scope.$watch val, (n,o) ->
return if n == o
props = {}
props[a] = n
reactComponent.setProps props
# unmount on $destroy
element.on '$destroy', -> React.unmountComponentAtNode element[0]
}
#-- Demo code --#
Hello = React.createClass
displayName: 'Hello'
componentDidMount: -> console.log 'componentDidMount'
componentWillUnmount: -> console.log 'componentWillUnmount'
componentDidUpdate: -> console.log 'componentDidUpdate'
render: ->
React.DOM.span null,'Hello '+@props.name+'!'
demo = angular.module 'demo',['react']
DemoCtrl = ($scope) ->
$scope.show = true
$scope.user =
name: 'Andreas'
<!DOCTYPE html>
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script src="http://fb.me/react-0.8.0.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div ng-app="demo" ng-controller="DemoCtrl">
<input type="text" ng-model="user.name"/><br>
Your name is {{user.name}}<br><br>
<input type="checkbox" ng-model="show"/>
Show Hello component<br><br>
<!-- Test adding/removing component from page -->
<div ng-if="show">
<div react-attach="Hello" react-prop-name="user.name"></div>
</div>
</div>
</body>
</html>
@wallrat
Copy link
Author

wallrat commented Jan 8, 2014

Some glue-code to use React components in AngularJS apps.

Try demo at http://jsbin.com/ENILAqEY/1/edit?html,js,output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment