JSFiddle - React, Tailwind, and code Playground
by Premchand R
HTML
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName"><!-- Input entered here -->
<br>Input is : <strong>{{firstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}<!-- How do I automatically updated it here? -->
</div>
</div>
JavaScript
// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var data =
{
FirstName: ''
};
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});
myApp.controller('FirstCtrl', function( $scope, Data ) {
$scope.firstName = '';
$scope.$watch('firstName', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setFirstName(newValue);
});
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
if (newValue !== oldValue) $scope.firstName = newValue;
});
});