Recently, I delved into AngularJS and encountered a challenge while attempting to share data between two ng-controllers within the same ng-app module using a factory. Surprisingly, the data (HTML input field) from controller1 mostly gets shared with controller2. However, a peculiar issue arises when I delete all contents of the input field, as the $watch functionality fails to work as expected. Describing this quirk in words is proving to be challenging, so I have included screenshots below for clarity.
Below is the snippet of my code:
<!DOCTYPE html>
<html>
<head>
<% include ../partials/head %>
</head>
<body class="container" ng-app='myApp'>
<div ng-controller="ctrl1">
<input type="text" ng-model="firstName">
<br>
Input is : <strong>{{firstName}}</strong>
</div>
<div ng-controller="ctrl2">
Input should also be here: {{firstName}}
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
var data = {
FirstName: ''
}
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (x) {
data.FirstName = x;
}
}
});
myApp.controller('ctrl1', function ($scope, Data) {
$scope.firstName = ''
$scope.$watch('firstName', function(newVal){
if(newVal){Data.setFirstName(newVal);}
});
});
myApp.controller('ctrl2', function ($scope, Data) {
$scope.$watch(function(){return Data.getFirstName();}, function(newVal){
if(newVal){$scope.firstName = newVal;}
});
});
</script>
</body>
<footer>
<% include ../partials/footer %>
</footer>
</html>
For those interested, I have also shared a relevant jsfiddle link: http://jsfiddle.net/5LL3U/2/
Your assistance on this matter would be greatly appreciated. Thank you!