如何在其他控制器中观察变量 AngularJS

How to watch variables in other controllers AngularJS

我有一个名为 histogram demo 的组件,其中有一个单独的控制器,它有一个名为 $scope.selectedElements 的变量,我想在主 appCtrl 控制器中观察这个变量。如果没有 $rootScope,我将如何访问此变量。

主要HTML

<html lang="en-US" ng-app="histogram-test" ng-controller="appCtrl">

 <div  class="histogram-container"> <histogram-demo options = "options" data="data"></histogram-demo></div>
 </html>

App.JS

angular
.module('histogram-test')
.config(function ($httpProvider, usSpinnerConfigProvider) {
    $httpProvider.defaults.withCredentials = true;
    usSpinnerConfigProvider.setDefaults({
        // see http://spin.js.org/
        color: 'white',
        radius: 30,
        width: 8,
        length: 16,
        shadow: true,
    });
})
.controller('appCtrl', function ($scope, appConfig, $rootScope, auth, $state) {
/** HERE is where I want to watch $scope.selectedElements in Component.js **/}

Component.JS

angular
.module('histogram-test').component('histogramDemo', {
    bindings: {
        data: "=",
        options: "=",
    },
    templateUrl: templateUrl,
    controller: controller,
    controllerAs: 'vm',
});

function controller($state, $scope) { ...
$scope.selectedElements = []; ...}

您可以简单地考虑将一个方法传递给 component,并在您更改 selectedElements 时从组件调用该方法。此外,为了使您的应用程序性能更高,请通过使您的绑定使用<(单向绑定)来遵循单向数据流。

bindings: {
    data: "<",
    options: "<",
    selectedItemChange: '&'
},

然后你的指令元素看起来像

<histogram-demo 
   options="options" 
   data="data" 
   selected-item-changed="itemChanged(items)">
</histogram-demo>

并且每当您在控制器组件中更改 vm.selectedItems 变量时,请调用 vm.selectedItemChange({items: vm.selectedItems}),因此 histogram-demo 组件的使用者将具有接收 selectedItems 数组的方法.