Is it possible to link the entire service to the management area?

For example, this service:

services.factory('ElementsService', function () {

var currentElement = 'default element';

var service = {
    getCurrentElement: function () {
        return currentElement;
    },
    setCurrentElement: function (elmnt) {
        currentElement = elmnt;
    }
}
return service;

I often find it helpful to do the following from controllers:

controllers.controller('ElementsCtrl', function($scope, ElementsService) {

    $scope.elementsService = ElementsService;

});

To be able to bind utility variables in html and stay up to date if the variables are changed by another controller or service. For instance:

<p>The current element is : {{elementsService.getCurrentElement()}}</p>

My question is: is this normal or should I avoid this?

+4
source share
1 answer

I am sure that the concept is in order and retains the need to make several scope variables

Another way you can do this is to

angular.extend($scope, ElementsService );

Then in the view, you will immediately get access to the same data and methods that are returned from the factory

<button ng-click="setCurrentElement(someObj)">test</button>
+4
source

All Articles