[英]function in child controller called from parent view
I have a settings controllers that is responsible of saving settings of my web app. 我有一个设置控制器,负责保存我的Web应用程序的设置。
This SettingsController has a simple $scope.saveSettings method. 这个SettingsController有一个简单的$ scope.saveSettings方法。 The settings controller is associated with settings.html defined as follows: 设置控制器与settings.html关联,定义如下:
.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 (eg in main.html) they are not invoked, because the main/parent controller assosiaciated with the main view doesn't know anything about saveSettings(). 如果我想在settings.html之外(例如在main.html中)使用“保存设置”按钮,则不会调用它们,因为与主视图关联的主/父控制器对saveSettings()一无所知。
What can be done about things like that? 这样的事情该怎么办?
My main.html has the 我的main.html具有
that injects settings.html when the route path is /settings 当路径为/ settings时注入settings.html
You should put saveSettings() inside a Service and inject in all the controller in which you need to use saveSettings() function: 您应该将saveSettings()放在服务中,并注入需要使用saveSettings()函数的所有控制器:
//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. 请在这里阅读有关服务的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.