Skip to content
This repository has been archived by the owner on Jul 28, 2019. It is now read-only.

Scope functions #43

Closed
mackenrou opened this issue Feb 2, 2015 · 2 comments
Closed

Scope functions #43

mackenrou opened this issue Feb 2, 2015 · 2 comments

Comments

@mackenrou
Copy link

How to call a scope function from react component?

Could you put a simple example of how to call a function in angular controller from onClick event of a react component?

Thanks in advance!

@kasperp
Copy link
Collaborator

kasperp commented Feb 2, 2015

@mackenrou how about this modified version of the Hello example

var app = angular.module( 'app', ['react'] );

app.controller( 'mainCtrl', function( $scope ) {
  $scope.person = {
    fname: 'Clark', lname: 'Kent'
  }
  // add function to scope
  $scope.changeName = function() {
    $scope.person = { fname: 'Bruce', lname: 'Banner' };
  };
} );

var Hello = React.createClass( {
  propTypes: {
    fname: React.PropTypes.string.isRequired,
    lname: React.PropTypes.string.isRequired,
    changeName: React.PropTypes.func
  },

  onClick: function( e ) {
    // process event here

    // now call function from props 
    // this is the change name function declared on the controllers scope
    this.props.changeName();
  },

  render: function() {
    return <div>
       Hello {this.props.fname} {this.props.lname}
       <button onClick={this.onClick}>Change Name</button>
      </div>
    );
  }
} );

app.value( "Hello", Hello );

app.directive( 'hello', function( reactDirective ) {
  return reactDirective( Hello );
} );

View

<div ng-controller="mainCtrl" ng-app="app">
  <hello fname="person.fname" lname="person.lname" change-name="changeName"/>
</div>

@mackenrou
Copy link
Author

Ups! It's very simple!
Thank you.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants