I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply()
should solve this issue. However, I am encountering an error when trying to implement this solution.
https://docs.angularjs.org/error/$rootScope/inprog?p0=$apply
This is my script:
var roomsApp = angular.module('roomsApp', []);
roomsApp.controller('RoomListController', function RoomListController($scope, $http) {
$scope.refreshData = function () {
$http({
method: 'GET',
url: '<?=url('getRooms')?>'
}).then(function successCallback(response) {
$scope.rooms = response.data;
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
$scope.refreshData();
$scope.addRoom = function (title) {
if (title != "" && typeof title !== 'undefined') {
$http({
method: 'POST',
url: '<?=url('addRoom')?>',
data: {
title: title
}
}).then(function successCallback(response) {
$scope.refreshData();
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
$scope.$apply();
};
});
This is my Angular-HTML code:
<div class="row" ng-app="roomsApp">
<div class="col-md-8">
<div class="panel panel-default" ng-controller="RoomListController">
<div class="panel-heading">Rooms</div>
<div class="panel-body">
<ul class='list-group' ng-repeat="room in rooms">
<li class="list-group-item">{{room.title}}</li>
</ul>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default" ng-controller="RoomListController">
<div class="panel-heading">New room</div>
<div class="panel-body">
<div class="input-group input-group-lg">
<span class="input-group-addon" id="title">Title</span>
<input type="text" ng-model="title" class="form-control" placeholder="" aria-describedby="title">
</div>
<br>
<button ng-click="addRoom(title);" type="button" class="btn btn-primary pull-right"><span
class="glyphicon glyphicon-plus"></span></button>
</div>
</div>
</div>
</div>