Dimitri Danilov
Dimitri Danilov

Reputation: 1352

Inject a variable from Service to html

I am asked to debug some things in an angular JS app, problem is I dont know anything about this framework and I need to get this done.

I need to inject a variable from my service to a html template. So I thought I will need to get this variable from Controller, which get it from the Service.

For the moment I have this :

controller.js

$scope.fileURL = null;
var fileURL = ItemsService.fileURL;
$scope.fileURL.push(fileURL);

services.js

I declare this inside my service class :

this.fileURL = null;

and i declare it my method this way :

self.fileURL = fileURL;

But I got this error TypeError: Cannot call method 'push' of null And fileURL is defined and got a value in my method. Any idea why ?

Thanks

Upvotes: 0

Views: 40

Answers (1)

AlexS
AlexS

Reputation: 5345

more performant solution

Thanks to maurycy for his comments.

Making your service visible through $scope like this:

$scope.itemService = ItemService;

and using it in your template for example like this:

{{itemService.fileURL}}

will be more perfomant, less complex and have all other advantages as well.


old solution

Why don't you just pass through your variable:

In your service:

this.fileURL = "something";

in your controller:

$scope.fileURL = function() {
    return ItemsService.fileURL;
};

This way changes made in your service (like a update of fileURL will trigger an update of the view through the controller.


FYI:

If you define your $scope-variable like this:

Object.defineProperty($scope, 'fileURL', {
    get: function() {
        return ItemService.fileURL;
    },
    set: function(newValue) {
        ItemService.fileURL = newValue;

    }
});

You may also update the variable in the service from the controller AND childscopes will have the same functionality, since upon $scope.fileURL = 'different'; they won't introduce a new property fileURL which hides the original one and doesn't wire to the service anymore.

Upvotes: 2

Related Questions