简体   繁体   English

角度点击不适用于我的 div

[英]angular click won't work on my div

We're developing an angular site.我们正在开发一个角度站点。 I can't get the event to work on a div:我无法让事件在 div 上工作:

<div style="width: 100%; height: 30px;" (click)="alert('Hello!')"></div>

This works when I switch (click) to onclick:这在我切换(单击)到 onclick 时有效:

<div style="width: 100%; height: 30px;" onclick="alert('Hello!')"></div>

Why do I get the alert with onclick but not (click)?为什么我通过 onclick 收到警报而不是 (click)?

Angular expressions (what you have inside the (click) attribute value) are always evaluated on the component associated with the template.角度表达式(您在 (click) 属性值中拥有的内容)始终在与模板关联的组件上进行评估。 You may not use global variables or functions in an angular expression.您不能在角度表达式中使用全局变量或函数。 All the variables and function calls are always implicitly resolved on the component.所有变量和函数调用总是在组件上隐式解析。 There is no alert() method in your component, so that code can't work.您的组件中没有 alert() 方法,因此代码无法运行。

To make that work, you need要完成这项工作,您需要

(click)="showAlert('Hello')"

and, in the component code并且,在组件代码中

showAlert(message) {
  window.alert(message);
}

Note that I edited your post.请注意,我编辑了您的帖子。 If you're using (click) , then you're not using AngularJS.如果您使用(click) ,那么您没有使用 AngularJS。 You're using Angular.您正在使用 Angular。 They are not the same framework.它们不是同一个框架。

If you're really, using AngularJS, then (click) won't work because that's the syntax used in Angular, not AngularJS.如果您确实在使用 AngularJS,那么 (click) 将不起作用,因为这是 Angular 中使用的语法,而不是 AngularJS。 The syntax in AngularJS would be AngularJS 中的语法是

ng-click="showAlert('Hello');

and you would need the showAlert function to be defined on the $scope of the associated controller (all AngularJS expressions are evaluated on the $scope):并且您需要在关联控制器的 $scope 上定义 showAlert 函数(所有 AngularJS 表达式都在 $scope 上计算):

$scope.showAlert = function(message) {
  window.alert(message);
}

Knowing the name of the framework you're using, and reading the appropriate documentation, would be a good first step to progress.了解您正在使用的框架的名称并阅读适当的文档,将是取得进展的良好开端。

If you don't post your code we can't know what went wrong, but make sure you're declaring the function inside your controller's scope, if using "onclick" works fine for you, then you're declaring it wrong, it means the function is declared outside any angular application.如果您不发布您的代码,我们无法知道出了什么问题,但是请确保您在控制器范围内声明了该函数,如果使用“onclick”对您来说效果很好,那么您就是在声明它是错误的,它意味着该函数是在任何角度应用程序之外声明的。

the "ng-click" prop will only work for functions that are declared inside the current controller's scope ( since that's where angular looks for your function when you use ng-click ) “ng-click”道具仅适用于在当前控制器范围内声明的函数(因为当您使用 ng-click 时,这是 angular 查找您的函数的地方)

Thanks both, very new to Angular.感谢两位,对 Angular 非常陌生。 Yes, I was falsely assuming Angular v2 was synonymous with AngularJS.是的,我错误地认为 Angular v2 是 AngularJS 的同义词。 Thanks for informing me that it's not.谢谢你告诉我它不是。 It's Angular v2 that I'm using.我使用的是 Angular v2。

Here's the code that I've inherited by another developer (who knew Angular inside and out):这是我从另一位开发人员(从里到外都了解 Angular)继承的代码:

    <!-- filter -->
    <div class="filter" (click)="clickToFilter_Clicked()"> **<!-- This is where I'm having trouble -->**
...
    </div>

    <!-- data list -->
    <div class="data-list">
        <all-data-row *ngFor="let item of categoryRows; let last=last"
                        relativeWidth="100"
                        [item]="item.chartData"
                        [last]="last"
                        (click)="selectCategory(item.fullObject)" **<!-- This works somehow -->**
                        [selected]="selected">
        </all-data-row>
    </div>

In the typescript file:在打字稿文件中:

import { Component, ViewEncapsulation, OnInit, OnDestroy, Input } from '@angular/core';

@Component({
selector: 'all-data-page',
templateUrl: './all-data-page.component.html',
styles: [ require('./all-data-page.style.scss') ],
})
export class AllDataPageComponent implements OnInit {
@Input() allData: any;
@Input() type: any;

private criticalityChartData: any[] = [];
private categoryRows: any[] = [];
private selected: any = null;

private colors: any = {
    'Safeguards': {
        'MEC': '#8f8fc6',
        'MEC-P': '#ebb174',
        'BPCS': '#2eb9ba',
        'BPCS-T': '#5a96d0',
        'BPCS-C': '#c0db73',
        'SIS-A': '#e5cf2d',
        'SIS': '#f69c94',
        'Other LS': '#ea7474',
        'Other LS-T': '#50c0a4',
        'Other LS-C': '#81c341',
        'PRO': '#6f6db2',
        'ROUND': '#b94a9c',
        'PM': '#ca94c2',
        'OCC': '#1cac5c',
        'OTHER': '#d56853'
    }
};

ngOnInit(): void {
    this.allData.forEach((category) => {
        if (category != null && category.Title === this.type) {
            if (!!category.CriticalityPieChart) {
                this.criticalityChartData = category.CriticalityPieChart;
                category.Items.forEach((item) => {
                    this.categoryRows.push({
                        'fullObject': item,
                        'chartData': {
                            'ValueColor': item != null ? this.colors[this.type][item.Category] : '',
                            'Value': item != null ? item.Criticality : '0.0',
                            'ValueLabel': item != null ? item.Title : ''
                        }
                    });
                    if (this.selected === null) {
                        this.selected = this.categoryRows[0].fullObject;
                    }
                });
            }
        }
    });
}

**// This function gets called:**
selectCategory(category) {
    this.selected = category;
}

closeDetails() {
    this.selected = null;
}

**// This function doesn't get called:**
clickToFilter_Clicked() {
    alert("Clicked!");
}
}

I'm not seeing a spot in the code where functions are being assigned to $scope.我在代码中没有看到函数被分配给 $scope 的地方。 In the typescript above, selectCategory(...) works.在上面的打字稿中, selectCategory(...) 有效。 It's called from in the angular code.它是在 angular 代码中调用的。 Yet clickToFilter_Clicked() doesn't work (doesn't get called) even though it seems I'm doing the same thing:然而 clickToFilter_Clicked() 不起作用(不会被调用),即使我似乎在做同样的事情:

<div (click)="clickToFilter_Clicked()"></div>

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

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