A
A
Alexey2016-09-23 15:59:50
Angular
Alexey, 2016-09-23 15:59:50

Update service from directive in AngularJS?

Faced such a situation:
In general, the structure of the project is quite simple. There is a directive that, when the button is clicked, should increase the user's score by 1. The user's score is stored in the 'score' service (factory) .
Points are displayed through the controller:
vm.score = score; // Где score - это сервис
well, html:

<div class="indicator">
            <div class="scores" data-ng-bind="score.total"></div>
        </div>

I know that when changing a service through a directive, the Scope of the service remains the same. Hence questions:
1) What in my logic is not correct?
2) Where should public values ​​be stored?
3) In $rootScope or all the same in the service?
4) How can I still update the value from the directive in the service, while the service must change its value also in the controller?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Markus Kelvin, 2016-09-29
@azovl

1. it should be like this vm.score = scoreService.getScore();
2 It is better to store common data in services since they are Singleton, which means they have only one entity throughout the application. And can be called from anywhere
3 Better in services, rootScope use bad tone and practice
4 This is how you can do
scoreService has a local score variable and two getScore and setScore methods
Import scoreService into a directive and in the link function call the scoreService.setScore() method which increases the value of score.
Import scoreService into the controller and read the value of scoreService.getScore()
If you need a specific solution, let me know, but it's better to understand the logic than a specific solution

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question