简体   繁体   English

AngularJS通过嵌套组件向上传播更改

[英]AngularJS propagate changes up through nested components

Is there a pattern or best practice method to propagate events or changes up through nested components in Angular 1.x? 是否存在通过Angular 1.x中的嵌套组件传播事件或更改的模式或最佳实践方法?

for eg say we have custom components/directives in the following layout 例如说我们在以下布局中有自定义组件/指令

<my-container>
    <main-area>
        <nav-bar></nav-bar>
        <work-area></work-area>
    </main-area>
    <side-panel></side-panel>
</my-container>

If the nav-bar contains buttons and some of those buttons will perform actions in the side panel then I can see two choices 如果导航栏包含按钮,并且其中一些按钮将在侧面板中执行操作,那么我可以看到两个选择

  1. Create a service that holds the state of the button options and inject it where it's needed 创建一个保存按钮选项状态的服务,并将其注入到需要的位置
  2. Use a one-way data bind that calls a function in the parent component that will alter the value in that parent. 使用单向数据绑定来调用父组件中的函数,该函数将更改该父组件中的值。

eg 例如

<nav-bar onButtonPress="changeValue()">

The changeValue() function is in the main-area's controller changeValue()函数位于主区域的控制器中

I'd like to try to avoid $watches/$emits etc and keep the internal state of the components known and the scopes isolated with clearly defined inputs/outputs 我想尽量避免$ watches / $ emits等,并保持组件的内部状态已知,并用明确定义的输入/输出隔离范围

Thanks! 谢谢!

$broadcast sends messages down through the scope(s), where as $emit sends messages upward through the scope(s). $broadcast通过范围向下发送消息,而$emit通过范围向上发送消息。

Failing that you could use 2-way binding on your directives. 未能在指令上使用2向绑定。

So you would have; 这样你就可以了;

app.controller('MainArea', function($scope) {
    $scope.model = {};
    $scope.model.changeValue = function(){
        // do stuff in this function
    }
});

app.directive('mainArea', function() {
    return {
        restrict: 'E',
        controller: "MainArea"
    }
});

app.directive('navBar', function() {
    return {
        restrict: 'E',
        scope: {
            model: "=ngModel"
        },
        link: function(scope, el, attrs) {
            scope.changeValue = scope.model.changeValue;
        }
    }
});

Then your HTML would be; 然后,您的HTML将是;

<main-area>
    <nav-bar ng-model="model" ng-click="changeValue">
</main-area>

Something like that. 这样的事情。 I'm in a rush so it's a rough outline of the code . 我很着急,所以它是代码的粗略概述 The premise behind it is to basically use 2 way/1 way binding so you can pass down functionality from your parent controllers/directives. 它的前提是基本上使用2方式/ 1方式绑定,因此您可以从父控制器/指令传递功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM