0

I have a settings controllers that is responsible of saving settings of my web app.

This SettingsController has a simple $scope.saveSettings method. The settings controller is associated with settings.html defined as follows:

.config(['$locationProvider','$routeProvider', function ($locationProvider, $routeProvider) {

    $routeProvider.when('/widgets', { templateUrl: 'partials/widgets.html', controller: 'widgetsController'});
    $routeProvider.when('/settings', { templateUrl: 'partials/settings.html', controller:'settingsController' });
    $routeProvider.otherwise({redirectTo: '/widgets'});
}])

If I want to have a button 'Save Settings' outside of settings.html (e.g in main.html) they are not invoked, because the main/parent controller assosiaciated with the main view doesn't know anything about saveSettings().

What can be done about things like that?

My main.html has the
that injects settings.html when the route path is /settings

kkudi
  • 1,625
  • 4
  • 25
  • 47

1 Answers1

0

You should put saveSettings() inside a Service and inject in all the controller in which you need to use saveSettings() function:

  //define a settingService
    angular.module('myApp').factory('settingsService', function() {  
        return {
            saveSettings: function() { //save settings logic }
        };
    });


function aCtrl($scope, settingsService) {
    settingsService.saveSettings(); // call save settings function that is inside the service
}

function settingsCtrl($scope, theService) {   
        settingsService.saveSettings(); // call save settings function that is inside the service
}

Please read HERE for more info about services.

Omar
  • 7,835
  • 14
  • 62
  • 108
  • the problem with this is that it needs to access the $scope of the parent as it hides certain elements on the parent. Services and factories work well when you're not messing with the $scope in your function. – kkudi Jun 04 '14 at 10:30