As I was trying to solve the problem of sharing data between two separate controllers, I encountered a curious issue.
Usually, I rely on services for this task and started creating a jsfiddle example, but unfortunately, I couldn't get it to function properly.
After some debugging, I noticed that if I dynamically created the properties in setActivePersonWorks(person)
, the dirty checking worked and the second controller displayed the correct value.
However, assigning the value in setActivePersonDoesNotWork()
did not yield the same result.
By using $timeout()
, I could confirm that DataService.badPerson
actually contained the correct data.
I'm puzzled by this behavior. It seems that using $apply()
would fix the issue, but why does creating values dynamically make things work smoothly?
Here is an example:
var myTest = angular.module("MyTest", []);
myTest.factory("DataService", function () {
var People = {
goodPerson: {},
badPerson: {},
setActivePersonWorks: function (person) {
People.goodPerson.name = person.name;
People.goodPerson.id = person.id;
},
setActivePersonDoesNotWork: function (person) {
People.badPerson = person;
}
};
return People;
});
function ViewController($scope, DataService, $timeout) {
$timeout(function () {
DataService.setActivePersonWorks({
id: 1,
name: "Good Mark"
});
DataService.setActivePersonDoesNotWork({
id: 2,
name: "Bad Mark"
});
}, 1000);
}
function DetailController($scope, DataService, $timeout) {
$scope.goodPerson = DataService.goodPerson;
$scope.badPerson = DataService.badPerson;
$timeout(function(){
$scope.message = "DataService has the value: " + DataService.badPerson.name + " but $scope.badPerson is " + $scope.badPerson.name;
}, 2000);
}
The <html/>
<div ng-app="MyTest">
<div ng-controller="ViewController"></div>
<div ng-controller="DetailController">
<h1>Works: {{goodPerson.name}}</h1>
<h1>Does Not Work: {{badPerson.name}}</h1>
{{message}}
</div>
</div>