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

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

user1987 Published in March 21, 2018, 6:41 am

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);

higherController.js listening for the emit

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

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

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO