I am trying to make two controllers comunicate via a service in Angularjs. The service 'playerFocus' works fine at the model level, but the view gets not updated. I refer in particular to the variable show inside the ModalDialogController, that turns correctly to true but remains false in the view. Here is the complete js:
(function(){
var players = [
{
id: 1,
name: 'Charles Foley',
photo: 'images/gem-01.gif'
},
{
id: 2,
name: 'Pippo',
photo: 'images/gem-02.gif'
},
{
id: 3,
name: 'Roberto',
photo: 'images/gem-03.gif'
}
];
var app = angular.module('soccer-match', []);
app.service('playerFocus', function(){
var subscriber = undefined;
this.sendMessage = function(mex){
subscriber(mex);
};
this.onMessage = function(callback){
subscriber = callback;
};
});
app.controller('PlayersListController', ['$scope', 'playerFocus', function($scope, playerFocus){
$scope.players = players;
$scope.playerDialog = function(p){
playerFocus.sendMessage(p);
};
}]);
app.controller('ModalDialogController', ['$scope', 'playerFocus', function($scope, playerFocus){
$scope.player = undefined;
$scope.show = false;
$scope.focusPlayer = function(p) {
for(i in players){
if(players[i].id == p){ // PROBLEM HERE
$scope.$apply( function(){
$scope.player = players[i];
$scope.show = true;
});
}
}
};
playerFocus.onMessage($scope.focusPlayer); // PROBLEM HERE
}]);
And the html template:
<!-- players list -->
<div id="players-list" ng-controller="PlayersListController">
<div ng-repeat="player in players">
<!-- player -->
<div class="player">
<img class="player-thumb" ng-src="{{player.photo}}"}}>
<div class="player-info">
<p>{{player.name}}</p>
<button ng-click="playerDialog(player.id)" type="button" class="btn btn-default player-info-btn">Info</button>
</div>
</div>
</div>
<!-- add player -->
<div class="player">
<img class="player-thumb" src="images/default.png"}}>
<div class="player-info">
<p>- ??? -</p>
<button type="button" class="btn btn-success player-info-btn">Nuovo Giocatore</button>
</div>
</div>
</div>
</div>
<!-- player modal dialog -->
<div ng-controller="ModalDialogController">
<div class="modal-dialog" ng-show="{{show}}">
{{player}}{{show}}
</div>
</div>
I searched for a solution the whole day, one being to use $apply to force the sync of model and view after the service callback, but I get this error. I am really confused on this and Angular docs are way too complicated for my level of understanding.