Problem: A controller variable vm.boatList (intended to be bound to a service variable, SearchService.boatList) is not updating with the service variable.
Code Snippets: Complete code at the bottom.
Controller
function SearchController($stateParams, SearchService) {
var vm = this;
vm.boatList = SearchService.boatList;
Service
function SearchService(BoatsDataService) {
var service = {
boatList: null,
getBoatList: getBoatList,
params: {}
};
return service;
Additional Data:
The getBoatList function called from the controller works - it logs data from the SearchService to the console. When I log vm.boatList immediately afterward, it's null.
Also, <div ng-repeat="boat in SearchController.boatList">...</div> only works when I assign directly to vm.boatList.
Console Output:
Array[3]
null
Complete Controller:
(function () {
'use strict';
angular.
module('trips').
controller('SearchController', SearchController);
SearchController.$inject = ['$stateParams', 'SearchService'];
function SearchController($stateParams, SearchService) {
var vm = this;
vm.boatList = SearchService.boatList;
vm.initialParams = getParams();
activate();
////////////////////
function activate() {
setInitialParams();
SearchService.getBoatList()
.then(function (data) {
SearchService.boatList = data;
console.log(SearchService.boatList); // Logs data.
console.log(vm.boatList); // Logs null.
})
.catch(function (error) {
console.log(error);
});
}
function getParams() {
var params = {
location: $stateParams.location,
passengers: $stateParams.passengers,
maxPrice: $stateParams.maxPrice,
minPrice: $stateParams.minPrice,
embark: $stateParams.embark,
disembark: $stateParams.disembark,
category: $stateParams.category
};
return params;
}
function setInitialParams() {
SearchService.params = getParams();
}
}
})();
Complete Service:
(function () {
'use strict';
angular.
module('trips').
factory('SearchService', SearchService);
SearchService.$inject = ['BoatsDataService'];
function SearchService(BoatsDataService) {
var service = {
boatList: null,
getBoatList: getBoatList,
params: {}
};
//$scope.$watch('service.params', function () {
// getBoatList().then(function (data {
// service.boatList = data;
// })
// }, true
//);
return service;
//////////////////////
function getBoatList() {
return BoatsDataService.BoatList
.query(service.params)
.$promise
}
}
})();
Recap: I don't know how to two-way bind, I guess.