Watch service's variable from another module inside a directive - javascript

I have two modules "core" and "ui".
The ui module depends on core. This is the code for my core.js :
var core = angular.module('core', [ 'ngRoute' ]);
//Services
core.service('httpInformationService', function() {
this.requestCount = 0;
this.responseCount = 0;
this.incrementRequest = function() {
this.requestCount++;
console.log('incrementRequest:' + this.requestCount);
};
this.incrementReponse = function() {
this.responseCount++;
}
this.decrementRequest = function() {
this.requestCount--;
console.log('decrementRequest:' + this.requestCount);
};
this.decrementResponse = function() {
responseCount--;
}
this.getRequestCount = function() {
return requestCount;
}
this.getResponseCount = function() {
return responseCount;
}
});
//Service provider
core.provider("httpServiceInformationProvider", function() {
var provider = {};
provider.$get = ['httpInformationService', function( service ) {
return service;
}];
return provider;
});
//HTTP Interceptor
core.factory('coreHttpInterceptor' ,function( httpInformationService ){
var coreHttpInterceptor = {
request: function(config) {
httpInformationService.incrementRequest();
return config;
},
response: function(response) {
httpInformationService.decrementRequest();
return response;
}
}
return coreHttpInterceptor;
});
var config = {
base_url: enviromnent_url,
}
core.value('config', config);
core.config(function( $interpolateProvider ) {
$interpolateProvider.startSymbol( "[[" ).endSymbol( "]]" );
});
core.config(function( $httpProvider ) {
$httpProvider.interceptors.push('coreHttpInterceptor');
});
This is my ui.js code:
var ui = angular.module('ui',[ 'core' , 'ui.bootstrap' ]);
ui.directive( "shLoadify" , function( httpServiceInformationProvider ){
return {
restrict: "AE",
link: function(scope, element, attrs) {
element.bind( "click", function() {
element.text("Loading...");
element.prop( "disabled", true );
});
},
controller: function($scope) {
$scope.$watch('httpServiceInformationProvider', function(oldValue, newValue){
console.log(oldValue + ' ' + newValue);
}, true);
}
}
});
As you can see i am trying to access requestCount property of httpInfomationService from within my controller using $scope.watch.
The problem is newValue and oldValue is always null. Why is that so?

Approach 1
If you want to perform some action whenever your requestCount variable gets changed which is part of service, you need to broadcast/emit which then you can listen through on. But in this case you need to pass the scope in your service which is not recommended.
var app = angular.module('app',['app1']);
app.service('myService',function($rootScope){
this.requestCount=1
this.incrementRequestCount=function(){
this.requestCount++
$rootScope.$broadcast('requestCountChanged', { message: this.requestCount });
}.bind(this)
})
app.controller('myController',['$scope','myService',function($scope,myService){
$scope.$on('requestCountChanged', function(event, args) {
// You will find the updated requestCount in args
});
$scope.click= myService.incrementRequestCount;
}])
var app1 = angular.module('app1',[]);
app1.controller('mySecondController',['$scope','myService',function($scope,myService){
$scope.$on('requestCountChanged', function(event, args) {
// You will find the updated requestCount in args
});
}])
Approach 2
Without passing scope in the service
var app = angular.module('app',['app1']);
app.service('myService',function(){
this.requestCount=1
this.incrementRequestCount=function(){
debugger;
this.requestCount++
}.bind(this)
})
app.controller('myController',['$scope','myService','$rootScope',function($scope,myService,$rootScope){
$scope.click=function(){
myService.incrementRequestCount();
$rootScope.$broadcast('requestCountChanged', { message: myService.requestCount });
}
}])
var app1 = angular.module('app1',[]);
app1.controller('mySecondController',['$scope','myService',function($scope,myService){
$scope.$on('requestCountChanged', function(event, args) {
// You will find the updated requestCount in args
});
}])
Approach 3
You can only attach watch to those properties which are actually in the scope otherwise you cannot have watch for those properties. So just add requestCount on you scope than you can easily detect its changes using watch and then use broadcast/emit approach.
var app = angular.module('app',['app1']);
app.service('myService',function(){
this.requestCount=1
this.incrementRequestCount=function(){
debugger;
this.requestCount++
}.bind(this)
})
app.controller('myController',['$scope','myService','$rootScope',function($scope,myService,$rootScope){
$scope.requestCount=myService.requestCount
$scope.$watch('requestCount',function(n,o){
debugger;
if(n!=o)
{
$rootScope.$broadcast('requestCountChanged', { message: n });
}
})
$scope.click=function(){
myService.incrementRequestCount();
$scope.requestCount=myService.requestCount
}
}])
var app1 = angular.module('app1',[]);
app1.controller('mySecondController',['$scope','myService',function($scope,myService){
$scope.$on('requestCountChanged', function(event, args) {
// You will find the updated requestCount in args
});
}])

Related

How to not minify a single variable?

In my case, using AngularJS, i have a json with some configurations that can be used in controllers.
The problem happens when i minify the application and the controller variables name does not match with the json.
Is there a way to not minify a single variabe?
My code:
setting.json
{
"settings": {
"adIndex": 3
}
}
controller:
function settingsService($q, $http, $log) {
var settings = {
adIndex: 0
};
var service = {
init: init,
getAdIndex: getAdIndex
};
return service;
function init() {
var deferred = $q.defer();
$http.get('assets/settings/settings.json').then(function(response) {
var loaded = response.data.settings;
if (loaded) {
settings = angular.extend(settings, loaded);
}
deferred.resolve(settings);
}, function(error) {
$log.info('Error loading settings', error);
deferred.reject(error);
});
return deferred.promise;
}
function getAdIndex() {
return settings.adIndex;
}
}
UPDATE
After your suggestions i made some changes on code, but the problem not yet resolved.
The code in controller is now:
function settingsService($q, $http, $log) {
var settings = {
'adIndex': 0
};
var service = {
init: init,
getAdIndex: getAdIndex
};
return service;
function init() {
var deferred = $q.defer();
$http.get('assets/settings/settings.json').then(function(response) {
var loaded = response.data['settings'];
if (loaded) {
settings = angular.extend(settings, loaded);
}
deferred.resolve(settings);
}, function(error) {
$log.info('Error loading settings', error);
deferred.reject(error);
});
return deferred.promise;
}
function getAdIndex() {
$log.debug('Object: ', settings); // result: settings { adIndex: 3 }
$log.debug('Value: ', settings['adIndex']); // result: 0
return settings['adIndex'];
}
}
How can 'adIndex' have 2 different values in logs?
var settings = {
"adIndex": 0 // quotes around the key, JSON style
};
Not 100% sure how your minifier will handle this, but usually they can not modify string values. If the above doesn't work, you can do something slightly more verbose:
var settings = {};
settings['adIndex'] = 0;
In this case, the variable settings will be minified, but the string 'adIndex' will remain unchanged.

Angular JS: Increment a Counter in a Service From Controller

I'm trying to fetch a value from an API inside my service for a counter, and then increment on that counter inside my controller:
service
angular.module('app')
.factory('MyService', MyService)
function MyService($http) {
var url = 'URL;
return {
fetchTotal: function(p) {
return $http.get(url, { params: p })
.then(function(response) {
var total = response.data.meta.total;
return total;
}, function(error) {
console.log("error occured");
})
},
incrementCounter: function(){
total++;
}
}
}
controller
app.controller('Controller1', function ($scope, MyService) {
var params = {
...
}
MyService.fetchTotal(params).then(function(response) {
$scope.counter = response;
});
$scope.incrementCounter = function(){
MyService.incrementCounter();
}
});
view
<div ng-controller="Controller1">
{{ counter }}
<span ng-click="incrementCounter()">increment</span>
</div>
I can't work out how increment on that total I get back from the API with an ng-click. Is this possible?
Any help is appreciated. Thanks in advance!
Angularjs services are singletons, so you can create variables and share it among controllers.
Notice below how variable total is initialized in the service. Same variable is used for interaction with the controllers by using the getCounter() method.
Also notice the init() method. Your controller can call MyService.init first thing to initialize the total variable.
angular.module('app')
.factory('MyService', MyService)
function MyService($http) {
var url = 'URL';
var total = 0; /* or some other initial value*/
return {
init: function(){
$http.get(url, { params: p })
.then(function(response) {
total = response.data.meta.total;
}, function(error) {
console.log("error occured");
});
},
incrementCounter: function(){
total++;
},
getCounter: function(){
return total;
}
}
}
See plunker for demo: http://plnkr.co/edit/idSxgm0axk43ydThTbJF?p=preview
Looks like you are doing everything right, except the variable total.
You should initialize it in an upper level so that it is also visible from incrementCounter function:
function MyService($http) {
var url = 'URL;
var total = 0;
return {
fetchTotal: function(p) {
return $http.get(url, { params: p })
.then(function(response) {
total = response.data.meta.total;
return total;
}, function(error) {
console.log("error occured");
})
},
incrementCounter: function(){
total++;
}
}
}
Hope it helps

Using services to share state between controllers

I want to share 'state' between multiple controllers within my Angular app by using services. My code is below. The problem I'm running into is that the controller which initiates the change in state, through vm.toggleStatus(), is updated, but this state does not update in my other controller until I refresh the page.
controller1.js:
angular.module('gameApp')
.controller('PlayerActionsController', PlayerActionsController);
PlayerActionsController.$inject = ['$routeParams', 'playersService'];
function PlayerActionsController($routeParams, playersService) {
var vm = this;
var playerId = $routeParams.playerId;
var getplayerInfo = function() {
playersService.getPlayerInfo({
playerId: playerId
}).$promise.then(function(player) {
vm.player = player;
});
};
var init = function() {
getplayerInfo();
};
init();
vm.toggleStatus = function() {
playersService.toggleStatus({
playerId: playerId
}, {}).$promise.then(function() {
getplayerInfo();
});
};
}
controller2.js:
angular.module('gameApp')
.controller('HeaderController', HeaderController);
HeaderController.$inject = ['$routeParams', 'playersService'];
function HeaderController($routeParams, playersService) {
var vm = this;
vm.playerId = $routeParams.playerId;
var getPlayerInfo = function() {
playersService.getPlayerInfo({
playerId: vm.playerId
}).$promise.then(function(player) {
vm.player = player;
});
};
var init = function() {
getPlayerInfo();
};
init();
}
players.service.js:
angular.module('gameApp')
.factory('playersService', ['$resource',
function($resource) {
var base = '/api/players/:playerId/';
return $resource(base, {}, {
getPlayerInfo: {method: 'GET', url: base + 'playerInfo'},
toggleStatus: {method: 'PUT', url: base + 'toggleStatus'}
});
}]);
Services do not push data to controllers, controllers need to either pull data from the service or listen to data changes.
What you probably want to do is update your service to emit an event when data changes and then have your controllers listed to those events and update when the change occurs. Example:
//service toggleStatus
toggleStatus = function(data) {
... what it currently does.
$rootScope.$emit('StatusChangedEvent', newStatus);
... return promise;
}
// in your controllers
$rootScope.$on('StatusChangedEvent', function(evt, newStatus) {
$scope.status = newStatus;
});

AngularJS - ng-bind not updating

I have a controller which has a function to get some alerts from an API and update a count on the front-end of my site which is bound to the alert.
Unfortunately the ng-bind attribute I'm using doesn't seem to be updating the count live, even though a simple console.log() is telling me that the actual alert count is being updated in the controller.
Front-end
<div class="modeSelector modeSelector_oneUp" data-ng-controller="MyLivestockController as vm">
<a class="modeSelector-mode" data-ui-sref="my-livestock">
<div class="modeSelector-type">Alerts</div>
<img class="modeSelector-icon" src="/inc/img/_icons/envelope-black.svg" onerror="this.src=envelope-black.png" />
<span data-ng-bind="vm.alertCount"></span>
</a>
</div>
Controller
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
angular
.module('abp')
.controller('MyLivestockController', MyLivestockController);
})();
Service
(function() {
'use strict';
function userService($q, $sessionStorage, $localStorage, $filter, user) {
var service = this;
service.getAlerts = function(id) {
var deferred = $q.defer();
user.alerts({ userID: id }, function(response) {
if (response.hasOwnProperty('data')) {
// Convert dates to valid Date
angular.forEach(response.data, function(alert) {
/* jshint camelcase: false */
if (alert.created_at) {
alert.created_at = $filter('abpDate')(alert.created_at);
/* jshint camelcase: true */
}
});
deferred.resolve(response.data);
}
else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
angular
.module('abp')
.service('userService', userService);
})();
As you can see, I've got my getAlerts() function being called every time an alert is deleted, using the deleteAlert() function, but the <span data-ng-bind="vm.alertCount"></span> on the front-end only updates after refreshing the page, where I'd like it to update live.
Your bind is not updating because you change the value of alertCount outside of digest cycle of your angular app. When you refresh your app, the digest runs and thus your value gets updated. Wrap the update of the variable in $scope.apply() like so:
$scope.$apply(function(){
vm.alertCount = alertData.length;
});
This will force digest and update the value live.
If you have more values that are updated outside of digest (any callback, promise etc) you can force digest cycle by calling:
$scope.$apply();
Hope it helps.
EDIT -----
Given your update with full code, I see that you are not injecting scope anywhere in your controller, the controllers I write usually start like that:
(function () {
var app = angular.module('mainModule');
app.controller('myController', ['$scope', '$myService', function ($scope, $myService) {
//logic
}]);
}());
EDIT -----
Here is a quick go I had on your code:
(function() {
'use strict';
var app = angular.module('abp');
app.controller('MyLivestockController', ['$scope', 'userService', function($scope, userService) {
var vm = {};
$scope.vm = vm;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
//important, this is promise so we have to apply the scope to update view
$scope.$apply();
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}]);
})();
The general idea is:
you create an app (angular.module)
you create a controller in this app, with $scope injected
any values you want to be updated on your view, you add to $scope
if you have any $scope updates in a callback, event or promise, you wrap them in (or follow with) $scope.$apply call
I think this should work for you :)
I have attempted to reproduce your code below with a mock userService, and some slight modifications to the html view so we can more clearly see the alerts and delete them. I have not modified your Controller.
This appears to work, yes?
Which leads me to believe there may be some issue with the implementation of your userService. If you are able to post the relevant code, I can update this answer with a clarified solution.
UPDATE: As you've updated your question with the userService code, I've updated the below to more closely match. I still have a mock service standing in place of the user dependency of the userService. Additionally I made a couple of small edits to the Controller class so that while promises are still resolving we can see 'Updating...' in place of the alerts count.
This all still appears to work, unless I'm misunderstanding - will think on it more and update this 'answer' when I can think of where else to investigate for the source of the issue, see if we can at least reproduce it!
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
return userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id).then(function() {
vm.alertsNotification.isLoading = false; //put here, loading isn't really finished until after .getAlerts() is done
vm.alertsNotification.hasError = false;
});
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
vm.alertsNotification.isLoading = true;
return userService.getAlerts(id).then(function(alertData) { //return the promise so we can chain .then in .deleteAlert()
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
function userMock($q, $timeout, $log) {
var _alerts = {
data: [{
id: 1,
message: "He doesn't sleep, he waits..."
}, {
id: 2,
message: "He doesn't mow his lawn, he stands outside and dares it to grow."
}, {
id: 3,
message: "Some magicians can walk on water. He can swim through land."
}]
},
_currentUser = {
id: 'Q2h1Y2sgTm9ycmlz'
};
return {
getCurrentUser: function getCurrentUser() {
$log.log("getCurrentUser");
//return $q.when(_currentUser);
return $timeout(function() { //use $timeout to simulate some REST API latency...
return _currentUser;
}, 500);
},
getAlerts: function getAlerts(id) {
$log.log("getAlerts: " + id); //not doing anything with the id in this mock...
$log.log(_alerts.data);
//return $q.when(_alerts);
return $timeout(function() {
return _alerts;
}, 500);
},
deleteAlert: function deleteAlert(userId, id) {
$log.log("deleteAlert: " + userId + " :: " + id);
//return $q.when(_alerts);
return $timeout(function() {
for (var i = 0; i < _alerts.data.length; i++) {
if (_alerts.data[i].id === id) {
_alerts.data.splice(i, 1);
$log.log("alert found and deleted");
break;
}
}
$log.log(_alerts.data);
return _alerts;
}, 500);
}
};
}
function userService($q, $timeout, $log, userMock) {
var service = this;
service.getCurrentUser = userMock.getCurrentUser;
service.getAlerts = function(id) {
var deferred = $q.defer();
userMock.getAlerts(id).then(function(response) {
if (response.hasOwnProperty('data')) {
// Convert 'he' to 'Chuck Norris'
angular.forEach(response.data, function(alert) {
if (alert.message) {
alert.message = alert.message.replace(/he/gi, "Chuck Norris");
}
});
deferred.resolve(response.data);
} else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
service.deleteAlert = function(userId, id) {
var deferred = $q.defer();
userMock.deleteAlert(userId, id).then(function(response) {
deferred.resolve(response.data);
}, function(e) {
deferred.reject('DATA ERROR');
});
return deferred.promise;
};
return service;
};
angular
.module('abp', [])
.service('userMock', userMock)
.service('userService', userService)
.controller('MyLivestockController', MyLivestockController);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="abp">
<div data-ng-controller="MyLivestockController as vm">
<div>Alerts</div>
<span data-ng-bind="vm.alertsNotification.isLoading ? 'Updating...' : vm.alertCount"></span>
<div data-ng-repeat="alert in vm.alerts">
{{alert.id}}: {{alert.message}}
<button ng-click="vm.deleteAlert(alert.id)">Delete</button>
</div>
</div>
</div>

Scope of Datas not updating after a $http AngularJS

I can't understand why it does not update the $scope.user_free_status when I set a user free but when I unset the parameter it works perfectly. I need to reload page in one case and not the other...
The datas fetched are stored in the localstorage.
Here is the code:
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'InitialCtrl',
resolve: {
theUserFreeStatus: function(DataService) {
return DataService.getUserFreeStatus();
}
}
})
Controller:
.controller('InitialCtrl', function($scope, $state, DataService ,FreeService, SharedService, theUserFreeStatus) {
// Showing set free but not unset or not
if (FreeService.isSetFree()) {
$scope.showSetFree = false;
$scope.showUnSetFree = true;
} else {
$scope.showSetFree = true;
$scope.showUnSetFree = true;
}
// Show the Free status set when arriving on page/app
$scope.user_free_status = theUserFreeStatus;
// Set user as Free
$scope.setFree = function(activity, tags) {
FreeService.setFree(activity, tags).success(function() {
console.log($scope.user_free_status);
$scope.user_free_status = DataService.getUserFreeStatus();
console.log($scope.user_free_status);
$scope.showSetFree = false;
$scope.showUnSetFree = true;
SharedService.goHome();
})
}
//// Free status unset
$scope.unsetFree = function() {
FreeService.unsetFree().success(function() {
$scope.user_free_status = [];
$scope.showSetFree = true;
$scope.showUnSetFree = false;
SharedService.goHome();
});
};
})
The services:
.factory('FreeService', function(WebService, $localstorage, $ionicPopup, DataService, $sanitize, CSRF_TOKEN) {
var cacheFreeStatus = function(free_status) {
$localstorage.setObject('user_free_status', free_status)
};
var uncacheFreeStatus = function() {
$localstorage.unset('user_free_status')
}
return {
setFree: function(activity, tags) {
var status = { SOME STUFF BLABLABLA };
var setFree = WebService.post('setstatus/', sanitizeStatus(status));
setFree.success(function(response) {
console.log('available' + response.flash);
cacheFreeStatus(response.status_response);
})
setFree.error(freeError)
return setFree;
},
unsetFree: function() {
var details = {OTHER STUFF};
var unsetFree = WebService.post('unsetstatus/', details);
unsetFree.success(function(response) {
console.log('unset ' + response.flash);
uncacheFreeStatus(response.status_response);
})
unsetFree.error(freeError)
return unsetFree;
},
isSetFree: function() {
return $localstorage.get('user_free_status');
}
}
})
.service('DataService', function($q, $localstorage) {
return {
activities: $localstorage.getObject('activities'),
getActivities: function() {
return this.activities;
},
user_free_status: $localstorage.getObject('user_free_status'),
getUserFreeStatus: function() {
return this.user_free_status;
}
}
})
* Local Storage Service
------------------------------------------------------*/
.factory('$localstorage', ['$window', function($window) {
return {
set: function(key, value) {
$window.localStorage[key] = value;
},
unset: function(key) {
localStorage.removeItem(key);
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
setObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key) {
return JSON.parse($window.localStorage[key] || '{}');
}
}
}])
When setting the user's status, the console returns that the $http call worked but an empty array for the $scope variable I try to set. Once I reload the page I can see the updates displayed. If I unset the user's status, the $scope is properly updated without need to reload the page.
The Webservice is just the $http call.
What am I missing here to have the $scope.user_free_status updated correctly without having to reload the page??
Thanks for your time!
Your data service is injected as service but you have not appended the functions to this.rather you have returned it as part of literal like u do in factory

Categories