I have a side menu and its controller. In another controller I get the user data and want to update my menu items. How to achieve that ? I tried using $watch and services but to no success. Also I never used $rootScope so please avoid if it is not the only solution.
.controller('menuCtrl', function($scope) {
$scope.username = ""
})
.controller('afterloginCtrl', function($scope) {
var a = "this is username"
$scope.username = a // here I wish to update username in menuCtrl
})
Please let me if you need more code or details.
EDIT
Actually I update user info via database table, from their I am retrieving the username and other info. So menu controller needs to update with current values in database every time
You can use
localStorage
Use the following code in your first controller:
and the next controller:
As per the above comments your requirement is to persistent the username if user closes app and reopens.So, by using service or factory data will be lost once app reload or close.
Work around :
You can use
localStorage
to store username and can also access the data across controllers.Code :
You can create a common factory service that will save and return the saved local storage data based on the key.
In controller :
Inject the
storageService
dependency in the controller to set and get the data from the local storage.If you are using service or factory data will be lost after page refresh. You Can use browser session storage.
You can to use some service for sharing data between controllers.
For example:
Obviously, you can also extend your service with some appropriate methods. etc.
Then you can use these methods: