I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers
after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer
, the new customer doesn't show up in allCustomers
. I suspect there's a problem with how I'm using promises. Can someone help me troubleshoot this?
controllers.js
// AngularJS Customer Controller
angular.module('CustomerModule')
.controller('CustomerController', function ($log, CustomerService) {
console.log("CustomerController initializing");
var custController = this;
custController.newCustomer = {};
custController.refresh = function () {
CustomerService.getAllCustomers().then(function (response) {
custController.allCustomers = response.data;
});
custController.newCustomer = {};
};
custController.createCustomer = function (customer) {
CustomerService.createCustomer(customer).then(function (response) {
custController.refresh();
});
};
custController.refresh();
});
services.js
// AngularJS Customer Service
angular.module('CustomerModule')
.service('CustomerService', function ($http) {
var service = this;
service.getAllCustomers = function () {
return $http.get("http://localhost:8080/customers");
};
service.createCustomer = function (customer) {
console.log("Creating customer ", customer);
return $http.post("http://localhost:8080/customers", customer);
};
});
Additional app code:
// AngularJS App Configuration
var app = angular.module('CustomerModule', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '../dashboard.html',
controller: 'CustomerController',
controllerAs: 'custController'
})
.when('/dashboard', {
templateUrl: '../dashboard.html',
controller: 'CustomerController',
controllerAs: 'custController'
})
.otherwise({redirectTo: '/'});
}]);
index.html
<!DOCTYPE html>
<html lang="en" ng-app='CustomerModule'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<!-- Body content goes here -->
dashboard.html
<!-- Dashboard HTML content goes here -->