AngularJS:我怎样才能通过控制器之间的变量? [英] AngularJS: How can I pass variables between controllers?

查看:223
本文介绍了AngularJS:我怎样才能通过控制器之间的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个角控制器:

function Ctrl1($scope) {
    $scope.prop1 = "First";
}

function Ctrl2($scope) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

,因为它是不确定的,我不能用 CTRL1 CTRL2 。但是,如果我试图通过它像这样...

I can't use Ctrl1 inside Ctrl2 because it is undefined. However if I try to pass it in like so…

function Ctrl2($scope, Ctrl1) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

我得到一个错误。有谁知道如何做到这一点?

I get an error. Does anyone know how to do this?

Ctrl2.prototype = new Ctrl1();

也失败了。

注意:这些控制器无法相互嵌套

NOTE: These controllers are not nested inside each other.

推荐答案

在多个控制器共享变量的一种方法是的创建服务并要使用它注入它的任何控制器。

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

简单的服务,例如:

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

在控制器中使用该服务:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

这是非常漂亮的这个博客(第2课和特别)描述

This is described very nicely in this blog (Lesson 2 and on in particular).

我发现,如果你要绑定到这些属性在多个控制器,如果你绑定到一个对象的属性,而不是基本类型(布尔,字符串,数字)保留绑定的参考效果更好。

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

例如: VAR财产= {Property1:首先'}; 而不是 VAR属性='第一';

更新:(希望)使事情更加清楚是一个小提琴,显示了例如:

UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:


  • 绑定到共享价值的静态副本(在myController1)

    • 绑定到一个原语(字符串)

    • 绑定到一个对象的属性(保存到一个范围的变量)


    • 绑定到一个返回功能的原语(字符串)

    • 绑定到对象的属性

    • 双向绑定到一个对象的属性

    这篇关于AngularJS:我怎样才能通过控制器之间的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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