Seeking a more efficient way to accomplish the following:
This is my service:
dashboardApp.service('MessagesService', function () {
var message = "";
this.update = function (new_message) {
message = new_message;
};
this.get = function () {
return message;
}
});
Now, let's consider this controller:
dashboardApp.controller('GroupPageController', function($scope, MessagesController){
$scope.message = MessagesController.get();
})
The $scope.message variable is used in my HTML page like this:
<h3 ng-bind="message"></h3>
Additionally, there is a second controller:
dashboardApp.controller('ChangeController', function($scope, MessagesController, $http){
$scope.sendEmail = function () {
$http({
method: "post",
url: "/enterprises/vouchers/_send",
data: {
group_id: group_id,
group_student_ids: group_student_ids
}
}).success(function (response) {
MessagesService.update(response.message);
}).error(function () {
console.log("failed")
});
}
})
When a button is clicked in the above controller, it fetches data from a web API and updates the variable within the service. The expectation is for the $scope.message variable in the first controller to update as well, reflecting the change on the HTML page. However, this does not occur as desired. As a solution, I am currently using $watch:
$scope.$watch(function () {
return MessagesService.get();
}, function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.message = MessagesService.get();
}
});
Though the current setup works effectively, some sources discourage the use of $watch within controllers.
Is there an alternative approach to achieve this functionality without relying on $watch?