javascript - 如何在其他 Controller AngularJS 中观察变量

标签 javascript angularjs binding components angularjs-components

我有一个名为 histogram demo 的组件,其中有一个单独的 Controller ,其中有一个名为 $scope.selectedElements 的变量,我想在主 appCtrl 中查看此变量> Controller 。如果没有 $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 **/}

组件.JS

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

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

最佳答案

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

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

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

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

每当你改变时vm.selectedItems Controller 组件内的变量,请调用 vm.selectedItemChange({items: vm.selectedItems}) ,所以 histogram-demo 的消费者组件将具有接收 selectedItems 的方法数组。

关于javascript - 如何在其他 Controller AngularJS 中观察变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832616/

相关文章:

javascript - 没有水平滚动条的jquery图像动画

javascript - 如何在 JS 函数中正确创建按钮监听器

javascript - 使用图像渲染 : pixelated; causes moving image to ripple a vertical pixel line

angularjs - 有时不显示AngularJS中的Google登录按钮

c# - 以编程方式将 ObservableCollection 绑定(bind)到 ListBox

c++ - 绑定(bind)的不是一个值,而是一个函数(获取这个函数的值)

c# - 如何将基于键的字典值绑定(bind)到代码隐藏中的 TextBlock?

javascript - 仅返回对象中的重复元素

javascript - angular js中区分大小写的过滤器而不使用用户定义的过滤器

ruby-on-rails - Rails 4.1 ActionController::UnknownFormat 错误响应使用 AngularJS