Flignats
Flignats

Reputation: 1274

Moving a function from Controller to Service in AngularJS

I have the following in my Controller:

    $scope.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

and in my HTML:

{{getParameterByName('test')}}

I'd like to move the function into a service to reuse this piece of code across other controllers.

I moved the function into a controller and renamed $scope.getParameterByName to this.getParameterByName

I made sure to inject the module and service into my controller.

In my controller I added the following code:

$scope.getParameterByName = function (name) {
    newService.getParameterByName(name);
};

However, now the expression in my HTML does not render the result. If I add the following to my service:

console.log(results[1]);

it is logging the correct result. What am I missing in my controller/HTML to render the expression properly again?

Upvotes: 1

Views: 526

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You missed to return the result value from your method.

$scope.getParameterByName = function (name) {
    return newService.getParameterByName(name);
};

More elegant solution would be just bind the reference of service method to scope variable

$scope.getParameterByName = newService.getParameterByName; //referenced service method

Upvotes: 1

Related Questions