使用表达式`("&")` 绑定将数据从 AngularJS 组件传递到父作用域 [英] Using expression `("&")` binding to pass data from AngularJS component to parent scope

查看:17
本文介绍了使用表达式`("&")` 绑定将数据从 AngularJS 组件传递到父作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法从角度组件输出绑定函数访问控制器范围

我正在尝试从仪表板 component 访问我的家庭控制器范围,但它未定义.

我也尝试了第二种方法,但我的函数变量未定义.

我使用 Angular 1.5 和 Typescript

第一种方法:

家庭控制器 HTML:

<dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged"></仪表板组件>

家庭控制器js:

命名空间 app.dashboard {'使用严格';类家庭控制器{静态 $inject:Array= ['$window'];构造函数(私有 $window:ng.IWindowService){}私有 onTileTypeChanged(tile:ITile) {控制台日志(瓷砖);//定义和工作控制台日志(这个);//没有定义的}}有角的.module('app.dashboard').controller('HomeController', HomeController);}

仪表板控制器js:

angular.module('app.dashboard').component('仪表板组件', {templateUrl: 'app/dashboard/directives/dashboard-container.html',控制器:仪表板组件,controllerAs: 'DashboardCtrl',绑定:{onTileTypeChanged: "&";}});this.onTileTypeChanged()(tile);

第二种方法:

家庭控制器 HTML:

<dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged()"></仪表板组件>

仪表板控制器js:

this.onTileTypeChanged(tile);

在这里我得到了相反的结果:

private onTileTypeChanged(tile:ITile) {控制台日志(瓷砖);//没有定义的控制台日志(这个);//定义和工作}

解决方案

tl;dr;见下面的演示

您正在使用表达式绑定.

angular.module('app.dashboard').component('仪表板组件', {templateUrl: 'app/dashboard/directives/dashboard-container.html',控制器:仪表板组件,controllerAs: 'DashboardCtrl',绑定:{onTileChange: "&";}})t

要将事件数据从组件传送到父控制器:

实例化dashboard-component:

</仪表板组件>

在组件控制器中使用 locals 调用函数:

this.onTileChange({$tile: tile});

注入本地变量的约定是使用 $ 前缀命名它们,以将它们与父作用域上的变量区分开来.

来自文档:

<块引用>
  • &&attr - 提供了一种在父作用域的上下文中执行表达式的方法.如果未指定属性名称,则假定属性名称与本地名称相同.给定 和隔离范围定义 scope: { localFn:'&myAttr' },隔离范围属性 localFn 将指向 count = count + value 表达式的函数包装器.通常希望通过表达式将数据从隔离作用域传递到父作用域.这可以通过将局部变量名称和值的映射传递到表达式包装器 fn 中来完成.例如,如果表达式是 increment($amount) 那么我们可以通过将 localFn 调用为 localFn({$amount: 22}) 来指定金额值.

-- AngularJS 综合指令 API 参考


使用表达式(&")绑定传递数据的DEMO

angular.module("app",[]).directive("customDirective",function() {返回 {范围: {onSave: '&',},模板:`<字段集><输入 ng-model="消息"><br><button ng-click="onSave({$event: message})">保存</button></fieldset>`,};})

<script src="//unpkg.com/angular/angular.js"></script><body ng-app="app"><custom-directive on-save="message=$event"></custom-directive><br>消息={{消息}}

Can't access controller scope from angular component output binding function

I'm trying to access my home controller scope from dashboard component but it's undefined.

I also tried a second approach but then my function variable is undefined.

I'm using Angular 1.5 with Typescript

FIRST APPROACH:

Home controller HTML:

<div class="home-container">
    <dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged">
    </dashboard-component>
</div>

Home controller js:

namespace app.dashboard {
    'use strict';

    class HomeController {
        static $inject:Array<string> = ['$window'];

        constructor(private $window:ng.IWindowService) {

        }

        private onTileTypeChanged(tile:ITile) {
            console.log(tile); // DEFINED AND WORKING
            console.log(this); // NOT DEFINED
        }
    }

    angular
        .module('app.dashboard')
        .controller('HomeController', HomeController);
}

Dashboard controller js:

angular.module('app.dashboard')
    .component('dashboardComponent', {
        templateUrl: 'app/dashboard/directives/dashboard-container.html',
        controller: DashboardComponent,
        controllerAs: 'DashboardCtrl',
        bindings: {
            onTileTypeChanged: "&"
        }
    });

this.onTileTypeChanged()(tile);

SECOND APPROACH:

Home controller HTML:

<div class="home-container">
    <dashboard-component on-tile-type-changed="HomeCtrl.onTileTypeChanged()">
    </dashboard-component>
</div>

Dashboard controller js:

this.onTileTypeChanged(tile);

And here I'm getting the opposite:

private onTileTypeChanged(tile:ITile) {
    console.log(tile); // NOT DEFINED
    console.log(this); // DEFINED AND WORKING
}

解决方案

tl;dr; see Demo below

You are using expression binding.

angular.module('app.dashboard')
    .component('dashboardComponent', {
        templateUrl: 'app/dashboard/directives/dashboard-container.html',
        controller: DashboardComponent,
        controllerAs: 'DashboardCtrl',
        bindings: {
            onTileChange: "&"
        }
    })t

To communicate event data from a component to a parent controller:

Instantiate the dashboard-component with:

<dashboard-component on-tile-change="HomeCtrl.onTileChange($tile)">
</dashboard-component>

In the component controller invoke the function with locals:

this.onTileChange({$tile: tile});

The convention for injected locals is to name them with a $ prefix to differentiate them from variables on parent scope.

From the Docs:

  • & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given <my-component my-attr="count = count + value"> and the isolate scope definition scope: { localFn:'&myAttr' }, the isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope. This can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment($amount) then we can specify the amount value by calling the localFn as localFn({$amount: 22}).

-- AngularJS Comprehensive Directive API Reference


DEMO of using expression ("&") binding to pass data

angular.module("app",[])
.directive("customDirective",function() {
    return {
        scope: {
            onSave: '&',
        },
        template: `
            <fieldset>
                <input ng-model="message"><br>
                <button ng-click="onSave({$event: message})">Save</button>
            </fieldset>
        `,
    };
})

<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
    <custom-directive on-save="message=$event">
    </custom-directive>
    <br>
    message={{message}}
</body>

这篇关于使用表达式`("&amp;")` 绑定将数据从 AngularJS 组件传递到父作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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