Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An Example of How to Use React from AngularJS
window.UIControls.CountryField = React.createClass
mixins: [CountriesMixin]
getInitialState: -> {code: @props.data}
changeCountry: (evt) ->
code = evt.currentTarget.value
@setState(code: code)
@props.onChange(code) if @props.onChange?
renderCountries: ->
_.map @getCountries(), (country, code) ->
`<option key={code} value={code}>{country}</option>`
render: ->
`<select value={this.state.code}
className='ra-country-field form-control'
onChange={this.changeCountry}>
{this.renderCountries()}
</select>`
class window.RenderReactComponent
constructor: (@logger, @scope, @componentName, @targetAttrName, @containerEl) ->
onChange : (value) ->
@logger.info "[RenderReactComponent] Data changed - #{@componentName}"
@transferToNg(value)
renderComponent: (data) ->
@logger.info "[RenderReactComponent] Rendering component - #{@componentName}"
data =
data : data
onChange: @onChange.bind(@)
reactComponent = @findReactComponent()
if reactComponent?
ReactDOM.render(React.createElement(reactComponent, data), @containerEl[0])
else
@logger.warn "[RenderReactComponent] Could not find - #{@componentName}"
transferToNg: (value) ->
targetObject = @scope.$parent
parts = @targetAttrName.split('.')
attrName = parts.pop()
_.each parts, (key) -> targetObject = targetObject[key]
# Update value from the parent scope and propagate the changes
(targetObject[attrName] = value) & @scope.$parent.$apply()
findReactComponent: ->
comp = window
_.each @componentName.split('.'), (v) -> comp = comp[v]
comp
window.CartApp.directive 'renderReactComponent', [
'utils.logging', (Logging) ->
{
restrict: 'A',
scope:
component: '@',
tabindex : '=',
ngModel : '='
link: (scope, el, attrs) ->
@component = new RenderReactComponent(
Logging, scope, scope.component, attrs.ngModel, el
)
scope.$watch 'ngModel', (value) =>
@component.renderComponent(value) if value?
}
]
%div{'render-react-component' => '', component: 'UIControls.CountryField', tabindex: '4', 'ng-model': 'currentUser.customer.country.iso_code'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.