AngularJS:如何分享范围函数和变量与其他控制器 [英] AngularJS: How to share scope functions and variables with other controllers

查看:167
本文介绍了AngularJS:如何分享范围函数和变量与其他控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个控制器在我的应用程序,在那里我有一些重复的code,如:

I've multiple controllers in my application, where I have some duplicate code like:

$scope.alert = null;

$scope.addAlert = function (message) {
    $scope.alert = { type: 'danger', msg: message };
};

$scope.clearAlerts = function () {
    $scope.alert = null;
};

什么是推荐的方式在分享这些AngularJS范围函数和变量?使用控制器继承?

What is the recommended way sharing these scope functions and variables in AngularJS? Using controller inheritance?

推荐答案

创建一个控制器,然后把该控制器域内常用方法。所以,你可以使用范围,其他地方并得到内部控制访问方法。

Create a one controller and then place common methods inside that controller scope. So that you can use that scope anywhere else and get access to method inside 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;
    };
});

此后使用该控制器的范围,通过使用它注入 $控制器,然后里面的大括号,你可以指定共同控制范围控制器的电流范围。

Thereafter use scope of this controller by inject it using $controller, and then inside curly brace you could assign common controller scope to the current scope of 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

});

或者更precise的方法是使用普通的共享服务,即暴露的两种方法和警报数据,可以通过注入内部服务名称使用此服务方法您控制器。

Or more precise way would be using common sharable service, that exposed two method and alert data, you can use this service method by injecting service name inside your controller.

服务

app.service('commonService', function($scope) {
    this.alert = null;

    this.addAlert = function(message) {
        this.alert = {
            type: 'danger',
            msg: message
        };
    };

    this.clearAlerts = function() {
        this.alert = null;
    };
});

内部控制服务的利用率

app.controller('testCtrl', function($scope, commonService) {

  console.log(commonService.alert);
  commonService.addAlert("Something");
  console.log("Updated Alert" + commonService.alert);

});

希望这清除你的概念,谢谢。

Hope this has cleared your concept, Thanks.

这篇关于AngularJS:如何分享范围函数和变量与其他控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆