Home Implementing a custom Angular service that uses $location and $emit
Reply: 1

Implementing a custom Angular service that uses $location and $emit

NJC
1#
NJC Published in 2017-12-07 21:36:57Z

I am trying to register a custom service in Angularjs that gets the URL, and then emits it back up to the higher level controller. I have 1. Registered the service with app.service 2. Passed in the name of the service to the lower controller 3. Am listening for the change in the higher level controller. I have it working when I duplicate the function in each controller, but I'm trying to refactor.

module.js registers the service

var app = angular.module('demo', ['ngRoute']);
app.service('changedUrlService', function() {
    this.getUrl = function(url) {
        $scope.emit('urlChange', url);
    }
});

lowerController.js controller that uses the service

angular.module('demo').controller("lowerController", ['$scope', '$http','$location' 'changedUrlService', function ($scope, $http, $location, changedUrlService)
{
  $scope.url = $location.url();
  $scope.findUrl = changedUrlService.getUrl($scope.url);
  $scope.findUrl();
}

higherController.js listening for the emit

$scope.$on('urlChange', function (event, item) {
  $scope.myUrl = item;
  console.log($scope.myUrl);
});

I have received a variety of errors as I tweaked this, including Unknown Provider, $scope not defined and more.

Rakesh Burbure
2#
Rakesh Burbure Reply to 2017-12-08 05:33:56Z

If you see this below code, you will understand you have not injected anything to the service. First you need to inject any other service and then only you can use it. But service is not the correct place to inject $scope.

var app = angular.module('demo', ['ngRoute']);
app.service('changedUrlService', function() { // No dependencies injected
    this.getUrl = function(url) {
        $scope.emit('urlChange', url); // Incorrect
    }
});

What you can do is, return the string from the string. Inject this service changedUrlService into the controller and use this to get the string. And not from the controller call the emit function.

Please let me know if it helps.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.392181 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO