I have been experimenting with the use of services in controllers and in particular binding scope properties on a controller to properties in a service.
In the code below I am finding the $scope.stockCountProp in my controller does not update unlike the $scope.stockCountFunc property which does increment correctly.
I found some posts suggesting you should use scoped functions for binding to service properties, why will the direct property binding approach not work?
<div ng-app="myApp" ng-controller="StockCtrl">
<h2>Stock Checker</h2>
<h3>Using a scoped function binding</h3>
Current Stock Level: {{stockCountFunc()}}
<br>
<h3>Using a direct property binding</h3>
Current Stock Level: {{stockCountProp}}
<br><button ng-click="updateStock()">Update Stock</button>
</div>
<script>
var app = angular.module('myApp', [])
.service('StockService', function() {
var StockModel = {};
StockModel.totalCount = 5;
StockModel.addStockItem = function() {
//Some API call here to add a stock item...
StockModel.totalCount++;
};
StockModel.getTotalCount = function () {
return StockModel.totalCount;
};
return StockModel;
})
.controller('StockCtrl', function($scope, StockService) {
$scope.stockCountFunc = StockService.getTotalCount;
$scope.stockCountProp = StockService.totalCount;
$scope.updateStock = function() {
StockService.addStockItem();
};
});
</script>
Demo fiddle https://jsfiddle.net/yh0o7987/2/