Created
January 8, 2014 15:39
-
-
Save anonymous/8318693 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
reactModule = angular.module 'react',[] | |
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 '[email protected]+'!' | |
demo = angular.module 'demo',['react'] | |
DemoCtrl = ($scope) -> | |
$scope.show = true | |
$scope.user = | |
name: 'Andreas' | |
age: 12 |
This file contains hidden or 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
<!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> | |
<div ng-if="show"> | |
<div react-attach="Hello" react-prop-name="user.name"></div> | |
</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment