Answer the question
In order to leave comments, you need to log in
How to properly manage data in angular 1.x?
Hello!
I am tormented by such a question: How to properly manage data in angularJS 1.x ?
The trick I'm using now:
angular.module('app')
.service( 'UserService', UserService )
.controller('UserController', UserController);
function UserService() {
this.user = {
settings: {
name: 'nikler'
}
}
}
function UserController(UserService) {
this.user = UserService.user;
}
user.settings.name
in the service, the changes will be displayed in the controller and vice versa. Answer the question
In order to leave comments, you need to log in
It's good when the areas of responsibility are distributed:
The controller is responsible for displaying data and user input.
And the service is responsible for updating and storing data.
In this approach, it is very easy to implement patterns such as undoing user changes and reverting to a previous version. Since it is always stored in the service.
Or, for example, to warn the user that there is unsaved data - before leaving the form, since you can compare the model from the controller with the version of the model in the service.
For good - there should be one data change point -> Service, and the controller should work with their copy
Can be done in different ways. The main thing from the very beginning is to decide who will make changes to the data. I would recommend that changes be made only in one place (for example, in the controller indicated in the example). If all and sundry change your data - other services, directives, other nested controllers, then you will very soon lose control over what is happening in your application and where the changes come from. The approach with a single person responsible for changing the data greatly simplifies life in applications with a complex architecture, although it sometimes requires unnecessary scrolling of event handlers up the component hierarchy.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question