使用可在Angular中的所有组件之间共享的范围

时间:2016-11-21 10:32:22

标签: angularjs angularjs-scope angularjs-components

我有一个方法的简单控制器:

app.controller('MyApp', function($scope) {
     $scope.myMethod() {...}
}

我还有很多输入字段组件(例如文本输入,数字输入,复选框,收音机等):

app.component('TextInput', {
    template: "<input type='text' ng-change='$ctrl.myMethodInComponent()' ng-model='inp' />",
    bindings: {
        myMethod: '&',
    },
    controller: function() {
        var ctrl = this;
        ctrl.myMethodInComponent = function() {
            /* some customizations */
            ctrl.myMethod();
        }
    }
});

我按以下方式创建此输入:

<text-input myMethod="myMethod()"></text-input>

一切都按预期工作,但问题是我有很多组件想要从主控制器使用方法'myMethod',我不想使用绑定('&amp;')将它传递给每个组件。 相反,我希望在mainScope之类的东西中使用此方法。我知道Angular提供了rootScope,但我不知道如何在我的情况下使用它。是否有可能将'myMethod'附加到一些主要(根)范围,这些范围将在我的所有组件之间共享?

2 个答案:

答案 0 :(得分:0)

您可以通过使用服务和工厂来实现您想要做的事情。接受它,如果你需要帮助或模板,请问我。

编辑模板

app.factory('myFactory', function($scope)
    var ret = {
        myMethod: myMethod,
        myMethodWithParams: myMethodWithParams
    }
    return ret;

    function myMethod() {...}
    function myMethodWithParams(param1, param2) {...}
}

现在,在您的控制器中,您可以将其用作依赖

app.controller('myController', function(myFactory) {
    var x = myFactory.myMethod();
    var y = myFactory.myMethodWithParams('hello', 'world');
});

答案 1 :(得分:0)

不确定这是您正在寻找的使用$ rootScope的用例,但这是一个解决方案:

    angular.module('myApp', [])

    .controller('MyController', function ($scope, $rootScope) {
        $scope.message = 'Hello from Controller 1';

        $scope.$watch('message', function () {
            $rootScope.$emit('controller1_scope_change', {
                message: $scope.message
            });
        });

    }).controller('MyController2', function ($scope, $rootScope) {
        $scope.message = 'Hello from Controller 2, here is the output from Controller 1:';

        $rootScope.$on('controller1_scope_change', function (event, args) {
            console.log('arguments received by the handler for the event: ', args);
            $scope.message2 = args.message;
        });

        // really hacky way of doing it
        /*var controller1_scope = angular.element(document.querySelector('#controller1')).scope();
        controller1_scope.$watch(function () {
            $scope.message2 = controller1_scope.message
        });*/
    });

View example here on codepen