I'm trying to tackle learning Angular in a fun project and ran into a issue where I haven't been able to find the solution.
When the page loads I get data from a Web API method and put the results in vm.Locations. These results end up being shown on the page using a repeater.
Later, createLocation get's called after Google's Places API returns back specific location data (a single record). That data get's posted to a Web API method and if it's successful I push the result of that into vm.Locations.
On the initial page load, everything loads properly. Later createLocation is called and the mc.locations.length binding shows the proper updated value, however the resulting elements in the repeater never update to show the new element.
I was thinking that $scope.$apply shouldn't be necessary since the array.length appears to be resolving correctly, but I am out of ideas for the moment.
Here are the main pieces:
Page:
<div ng-controller="MapController as mc">
<h1>Locations ({{mc.locations.length}})</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="location in mc.locations">
<td>{{location.Name}}</td>
<td>{{location.FormattedAddress}}</td>
</tr>
</tbody>
</table>
</div>
Controller:
function MapController($http) {
var vm = this;
var dataService = $http;
vm.locations = [];
vm.createLocation = function(location) {
var locationData = {
Name: location.name,
PlaceId: location.place_id,
FormattedAddress: location.formatted_address,
Latitude: location.geometry.location.lat(),
Longitude: location.geometry.location.lng()
}
var config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' }
}
dataService.post("api/Location/AddLocation", locationData)
.success(function (data, status, headers, config) {
vm.locations.push(data);
})
.error(function (data, status, header, config) {
alert(status);
});
}
function getAllSavedLocations() {
dataService.get("/api/Location/GetAllLocations")
.then(function (result) {
angular.extend(vm.locations, result.data);
vm.locations.forEach(function (place) {
bounds.extend(new google.maps.LatLng(place.Latitude, place.Longitude));
vm.addLocationToMap(place.Name, place.Latitude, place.Longitude);
});
},
function (error) {
handleException(error);
});
}
...
}