我的应用程序中有多个 Controller ,其中有一些重复的代码,例如:
$scope.alert = null;
$scope.addAlert = function (message) {
$scope.alert = { type: 'danger', msg: message };
};
$scope.clearAlerts = function () {
$scope.alert = null;
};
在 AngularJS 中共享这些作用域函数和变量的推荐方式是什么?使用 Controller 继承?
最佳答案
创建一个单一 Controller ,然后将通用方法放入该 Controller 范围内。这样您就可以在其他任何地方使用该范围并访问 Controller 内部的方法。
Controller
app.controller('commonCtrl', function($scope) {
$scope.alert = null;
$scope.addAlert = function(message) {
$scope.alert = {
type: 'danger',
msg: message
};
};
$scope.clearAlerts = function() {
$scope.alert = null;
};
});
此后通过使用 $controller
注入(inject)它来使用此 Controller 的作用域,然后在大括号内您可以将通用 Controller 作用域分配给 Controller 的当前作用域。
通用 Controller 的使用
app.controller('testCtrl', function($scope, $controller) {
//inject comomon controller scope to current scope ,
//below line will add 'commonCtrl' scope to current scope
$controller('commonCtrl', { $scope: $scope });
//common controller scope will be available from here
});
或者更精确的方法是使用公共(public)共享服务,它公开了两个方法和alert
数据,您可以通过在 Controller 中注入(inject)服务名称来使用此服务方法。
服务
app.service('commonService', function($scope) {
this.alert = null;
this.addAlert = function(message) {
this.alert = {
type: 'danger',
msg: message
};
};
this.clearAlerts = function() {
this.alert = null;
};
});
Controller 内部服务的使用
app.controller('testCtrl', function($scope, commonService) {
console.log(commonService.alert);
commonService.addAlert("Something");
console.log("Updated Alert" + commonService.alert);
});
希望这已经清除了您的概念,谢谢。
关于javascript - AngularJS:如何与其他 Controller 共享作用域函数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212545/