Where to save the model in angularJS application?

I'm still learning angularjs, and I have a problem understanding the difference between the $scope and model objects, and this is currently blocking me from organizing (using some best practices) my application.
As far as I understand, $scope should be read only (looked at some manuals where I heard it).

So when I download the application, I have to use service to get some data from the database and save it in model .

UPDATE

Right now, all the data that I get from the server is stored in the $ scope checksum, and I'm trying to transfer it to services and make the controller stupid.
I am also checking this article and I am trying to use the second or third option, but still cannot find a better way to implement it.
This is my service and controller:

 function dataService($http) { var service = { getToDoList: getToDoList, getToDoListByType: getToDoListByType, getToDoById: getToDoById }; return service; function getToDoList() { } function getToDoListByType() { } function getToDoById() { } } function toDoController($location) { var vm = this; vm.todos = []; vm.title = 'toDoController'; activate(); function activate() { return getToDos().then(function () { console.log("ToDos loaded"); }); } function getToDos() { return dataservice.getToDoList() .then(function (data) { vm.todos = data; return vm.todos; }); } } 

But in this implementation, the execution list is again in the controller.

Where should I store this list after I get it from the server and where should it be installed (from the controller or from the service) so that I can manipulate this list in a cached way (save it locally and update it periodically)?

I come from the C # world, and there I always used entity objects (for example, User, Product, Element, etc.) that fill this object in a loop and store it in a list. I can’t find a way, how should I use this approach in angular too, and if so, should it only be with properties?

I use one service to list and one service contain CRUD functions. If I load data into $scope from my model, how to update this area later if any other part of the code changes the data in my model?

Changes may come from another controller or, for example, be updated via SignalR. Also, as I heard, when I update the data in sight, since $scope should be read-only, do I need to update the service and again how and when to update $scope then?

I apologize if my question is too noob, but I would be grateful if someone could help me understand where to save what is in angular?

+6
source share
4 answers

The model is most often used in an architectural software template called Model-view-controller (MVC). You cannot understand how a model works without knowing the full picture. In this template, the web application is broken down into components to separate responsibilities. I will give you an example of the complete TODO code to see the real use of MVC. enter image description here

Model: take / process all domain data (most often you take it from the server). Here you create a transparent API that provides access to data that occurs with services. In the service, you get data from the server, you store it inside, and then you provide some functions that provide access, and when someone needs this data, he simply uses injection to access the service. Think of a service like a singlet data class, get / set, and other methods. Rule: if you do not know where something is happening, most likely it will serve. (FULL CODE)

 .factory('api', function ($resource) { 'use strict'; var store = { //HERE IS THE API todos: [], api: $resource('/api/todos/:id', null, { update: { method:'PUT' } } ), clearCompleted: function ()[..] delete: function (todo)[..] get: function () [..] insert: function (todo)[..] put: function (todo)[..] }; return store; }) 

Controller: in the images above, you can easily see what the controller receives and does not give user interaction. Controllers do not manipulate Dom. The data here goes from the view (user) to the controller, using the area (or using this inside the controller), and then control the model using the functions that we get by entering the service (model). Many times we cite the controller as an intermediary that violates the MVC rule by querying the model and passing the result to the view, that is, another name for the MVP template. The rule is this: your controllers should always be as compact as possible ( FULL CODE )

 .controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, store) { //store is the model, we make this in app.js //is the result of a factory we make up,and we named "api" var todos = $scope.todos = store.todos; [..] //in html we call removeTODO //<button class="destroy" ng-click="removeTodo(todo)"></button> //We use user interaction to manipulate the model! $scope.removeTodo = function (todo) { store.delete(todo);//we use the api we make }; [..] 

View: as you can see in the image, the model updates the view, not the controller. How? With directives and filters. Be careful, a view has only a data view (data binding). They do not contain complex logic. I want to be clear, in MVC, the view must access the model directly. Directives and filters provide this feature. If you want to perform DOM manipulation, you must use the directive (not the controller). Note: we put the dom manipulation inside the compilation function and directive links, and not in the controller. ( FULL CODE1 FULL CODE2 )

I have a problem understanding the difference between $ scope and model object

A sphere is just a reference to a model, as we see, but not a model! The scope is also used to interact with the user, the controller depends on the scope, and the controller depends on the model.

so can i manipulate this list in a cached way (save it locally and update it sometimes)?

There are many ways to solve this problem. We regularly use the observer pattern, but in angular there is another way to do this, which is better in most cases. Here is an example:

 angular .module("testApp", []) .service("myDataService", function(){ this.dataContainer = { valA : "car", valB : "bike" } }) .controller("testCtrl", [ "$scope", "myDataService", function($scope, myDataService){ $scope.data = function(){ //you get always the update data and never store tha data //to the controller return myDataService.dataContainer; }; }]); 

For more information check out this one , there are some amazing answers.

+4
source

Problem: You have deleted data. You want all your controllers to have access to it. You do not want each of them to receive it independently.

One way to do this in Angular: Use a service. Services are all same-sex. This means that your application will have only one instance of the service and can be used to exchange data. I looked at the link that you shared, and below is an example of the second sentence: "Service is a model and a service."

 function dataService($http) { var todos= []; this.getTodos = function() { return todos; }; this.getToDoList= function() { // use $http to get remote data and assign it to todos }; } 

Now you can do TodoService.getData () anywhere you entered it, say, your .run block, and from now on TodoService.getTodos () will return the same data as before.

Alternatively, you can use the service exclusively for receiving data, and not for storage (link of the 3rd sentence). For this, you will not store var todos in the service or have this.getTodos , you will only have the getData function (and other data receiving functions). Then from each controller, you run TodoService.getData () to run the general http get function.

Where should I store this list after receiving it from the server and where should it be installed (from the controller or from the service) so that I can manipulate this list in a cached way (save it locally and update it periodically)?

If you want to store and manipulate it in a cached way, you want to save your data in the service. Your controllers will receive data from the service. There are several articles in the section that use services for talking between controllers . They talk about using $broadcast to send your own events so that updating one controller updates other independent controllers.

Anyway: you want to bind the todos list to $scope in your controller. This will allow you to display its contents in your view and use Angular magic as a two-way binding. In your code:

 function toDoController($scope, dataService) { $scope.todos = []; activate(); function activate() { return getToDos().then(function () { console.log("ToDos loaded"); }); }; function getToDos() { return dataService.getToDoList() .then(function (data) { $scope.todos = data; return $scope.todos; }); }; } 

Then, in your opinion, you can simply refer to {{todos}} .

+2
source

Angular does not come with a tired way to store data.

Some projects dedicated to these and other related issues:

https://github.com/mgonto/restangular
https://github.com/adrianlee44/ng-backbone
https://github.com/paysavvy/immutable-angular

What I have done in the past is to write a models and collections module that stores data. These are just simple constructors.

 angular .module('app.models', []) .factory('app.models.User', ['$resource', function($resource) { function User(name) { this.name = name; } User.prototype.sayName = function() { console.log(this.name) }; User.prototype.getInfo = function(params) { $resource.get(params).then(res => { this.info = res.data; }); }; return User; }); 

And then in your view model you connect the view ... to the model!

 ['app.models.User', function Controller(User) { this.user = new User('bob'); }] <div> <button ng-click="vm.user.sayName()">say name</button> </div> 
+2
source

I have not read the exact same tutorials as yours, but I usually refer to the Angular Style Guide originally published by John Papa with significant feedback from the Angular community.

If you use SignalR to update your models in real time, I think you are looking for a one-way data flow concept. I don’t have a great resource to point you to this, but I saw some SignalR and Angular examples that you can find just looking back at the main idea.

In general, the goal is to receive updates from the server into your application. Therefore, if your controller updates the value, your data model is not updated with the controller code. Your application sends the record to the server, and the server sends the new value back to the AngularJS application.

Angular versions prior to 1.5 did not have the concept of one-way data binding, so if you use two-way ng-model binding, this is automatic, so you usually need to handle the value that you bind to as temporary and then synchronized state with the cached value or server when The user has edited the data.

Your question is quite wide, so if you need a more specific answer or “How to do it,” you can include some information about what type of application you are writing, and sometimes the size of the application (the number of controllers / features) will give an idea of ​​which methods will serve you best. Some of the best practices for very large applications look like anti-templates for simple weekend project applications.

+1
source

All Articles