I am trying to constantly update my value in the controller. Can get it to work with the initial property value but it does not update later on. I've tried so many ways of doing this, and went through so many threads but I can't make it work... I've almost gave up on this already as I have no idea what the problem is.
I am trying to avoid using broadcasting as much as I can in this situation. Can you spot something obvious I'm doing wrong?
angular.module('app',[])
.controller('mainCtrl', function(userService) {
var vm = this;
vm.livePropertyFromService = userService.getValue('property');
vm.incrementServiceProperty = function() {
userService.update('property', userService.user.property + 1);
console.log('userService.user.property = ', userService.user.property);
}
})
.service('userService', function($window) {
var service = this;
service.user = {
property: 0
};
service.update = function(propertyName, property) {
service.user[propertyName] = property;
};
return {
update: function(propertyName, property) {
service.user[propertyName] = property;
},
getValue: function(key) {
return service.user[key];
},
user: service.user
}
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
</head>
<body>
<div ng-controller="mainCtrl as vm">
<button ng-click="vm.incrementServiceProperty()">Increment property</button>
<span ng-bind="vm.livePropertyFromService"></span>
</div>
</body>
</html>