Let's talk about the React js for an instance.
When we want to bind the data between view and controller, we have to use setState/redux/flux. Here, setState/flux/redux is used for the data-flow. React has a uni-directional data-flow, which means, the changes we make in the view, don't automatically reflect in the controller. You have to explicitly call some method to pass the data.
Also, the data-flow is not only restricted to the binding. If you want to pass the data between components, you can use this mechanism. (Don't confuse it with binding)
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
In the code above, you can see how this.state.value
is updating.
In contrast to React, Angular has a two-way data binding. What it means is, you don't have to explicitly change the variable. It gets updated automatically when we change the view.
<script>
angular.module('changeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.counter = 0;
$scope.change = function() {
$scope.counter++;
};
}]);
</script>
<div ng-controller="ExampleController">
<input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
<input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
<label for="ng-change-example2">Confirmed</label><br />
<tt>debug = {{confirmed}}</tt><br/>
<tt>counter = {{counter}}</tt><br/>
</div>
Here, you can see, confirmed
is two-way bound, therefore, we don't need to update the state manually.