TL;DR - The $on
should change the value of practiceCount
...why isn't it? Here is codepen: http://codepen.io/anon/pen/qNERva
It's my third day practicing MEAN development, so I don't have too much experience with this.
So, I've got a controller MainController
. I want this controller to be available on static/constantly available elements (that won't show/hide on condition) such as my nav-bar, and its purpose is to broadcast global data such as the total number of X in the application.
app.controller('MainController', [ '$scope','$http', function($scope, $http){
$scope.practiceCount = 0;
$scope.$on('practiceInfo', function(event, practiceInfo){
$scope.practiceCount = practiceInfo.count;
});
}]);
I then have a PracticeController
controller. This controller is specifically for managing the Practices on this application (Practice in medical terms), i.e. creating/deleting/editing Practices.
app.controller('PracticeController', ['$scope', '$http', function($scope,$http){
//refresh function that fetches practices
var refresh = function(){
$http.get('/practices').success(function(response){
$scope.practices = response;
$scope.practiceCount = response.length;
$scope.$emit('practiceInfo', {
count: $scope.practiceCount
});
});
}
refresh();
$scope.createPractice = function(){
if($scope.practice)
$http.post('/practices', $scope.practice).success(function(response){
console.log(response);
refresh();
})
}
}]);
Finally, in my index.html
(template) file, I have hooked up the MainController
to the <ul>
of my nav-bar, and am trying to display practiceCount
, like such:
<ul ng-controller="MainController">
{{practiceCount}}
</ul>
My expectation according to my current understanding
Now... I don't know much about this yet but from my understanding, when I emit practiceInfo
with the new value stored in count
, then it should be received by MainController
, and the practiceInfo.count
property should be set as the new value of $scope.practiceCount
in MainController
... meaning its value has been changed/reset to whatever the result of the function reception was. With that, shouldn't the new number change automatically on the HTML?
It just stays as 0, which is how i initialized it in MainController
Advice would be much appreciated, on this issue, or anything else that's relevant.
Thanks.