标签: angular-directive

AngularJS 如何从指令访问控制器范围

我正在尝试从指令函数访问父控制器范围。当我尝试获取它的值时,$scope.$parent它会返回该对象。但是当我尝试从该对象访问任何变量时,它会返回Undefined

app.controller('myCtrl', function ($scope, $http, $timeout) {

    $scope.init = function(){

        $http.get('url.php').success(function(data){
            $scope.assignmentInfo = data.record;
        });

    };
});


app.directive('getInfo', [function(){
    return {
        restrict: 'A',
        scope:{
            data:'=',
            title: '='
        },
        link:function(scope, elem, attrs){
            scope.$watch('data.visible', function(val){
                // do something

            });
        },
        controller: function($scope) {
            console.log($scope.$parent); // return an object

            console.log($scope.$parent.assignmentInfo); // return undefined


        },
        templateUrl: 'template.html'
    };
}]);
Run Code Online (Sandbox Code Playgroud)

首先console.log($scope.$parent)返回以下输出: 在此输入图像描述

$scope.$parent.assignmentInfo返回underfined

我如何访问assignmentInfo

angularjs angular-directive angular-controller

2
推荐指数
1
解决办法
2642
查看次数

@viewchild for 指令始终返回元素引用而不是指令引用 - angular5

我目前正在开发一个项目,我需要根据组件传递一些 @input 值。因此,该指令将相应地发挥作用。但问题是我无法获得该指令的参考。相反,我只得到了 elementRef 作为回报。请参阅下面的 stackblitz 示例以获取更多参考。

https://stackblitz.com/edit/angular-feptw3

angular-directive angular angular5

2
推荐指数
1
解决办法
2422
查看次数

Ionic 4 showWhen hideWhen

我正在尝试对 web 和设备使用相同的 html,并且在某些情况下我需要显示/隐藏 web html 或设备 html。

Ionic 4中的showWhenhideWhen指令在哪里?如果它们消失了,它们是否被其他东西取代?

截至目前,我能找到的只是一些测试页面,但这并没有说明太多。

html ionic-framework angular-directive ionic4

2
推荐指数
1
解决办法
5725
查看次数

在 Angular 指令中使用 CSS 悬停属性?

这是指令,默认的。

import { Directive, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: '[newBox]'
})
export class BoxDirective {

  @Input() backgroundColor = '#fff';
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', this.backgroundColor);
  }

}
Run Code Online (Sandbox Code Playgroud)

现在,在悬停时,我希望改变背景颜色。我如何在指令中做到这一点?

css angular-directive angular2-directives angular

2
推荐指数
1
解决办法
1545
查看次数

ngStyle 与指令上调用函数之间的性能

主要区别是什么

<p [ngStyle]="getStyle()"> 
// getStyle returns a string like "color:blue" and some other attributes
Run Code Online (Sandbox Code Playgroud)

<p appStyle [status]="myStatus">
//directive get myStatus as a input and calculate the style of the tag
Run Code Online (Sandbox Code Playgroud)

我正在做维修电话,这些功能的应用getStylengStyle有很多(可能5K次)。我目前正在将样式计算更改为指令,因为我认为它更干净。

但是不知道对性能有多大影响。我怎么能测量它?

另一个问题,是否有文档/教程/书籍可以解释这样的事情?

谢谢

angular-directive angular angular5

2
推荐指数
1
解决办法
1092
查看次数

带有模拟结构指令的 Angular 测试组件失败

我正在尝试在组件测试中模拟结构指令,但出现错误。

以下测试失败并显示一条消息:

嵌入模板上的任何指令都未使用属性绑定 appSome。确保属性名称拼写正确,并且所有指令都列在“@NgModule.declarations”中。("[错误 ->] 测试

我嘲笑结构指令SomeDirectiveSomeMockDirectiveapp.component.spec.ts中定义。测试失败

如果我切换声明使其包含SomeDirective-测试通过

我想知道为什么我不能让它与模拟版本一起工作。

模板:

<h1 *appSome="true">TEST</h1>
Run Code Online (Sandbox Code Playgroud)

指令(生产种类:)):

@Directive({
  selector: '[appSome]'
})
export class SomeDirective implements OnDestroy {
  show: boolean;
  ...
}


Run Code Online (Sandbox Code Playgroud)

测试:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { Directive, NO_ERRORS_SCHEMA } from '@angular/core';

@Directive({
  selector: '[appSome]'
})
export class SomeMockDirective {}

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent, SomeMockDirective], // test is …
Run Code Online (Sandbox Code Playgroud)

angular-directive angular angular-test

2
推荐指数
1
解决办法
1091
查看次数

使用带有嵌套指令的 viewChildren 获取子项

我正在尝试在我的 angular 应用程序中实现一些功能。我创建了一个父指令appParent和另外两个指令appChildAbcappChildXyz.

我想要做的是,每当我appParent在元素上应用指令时,我想检查它的子元素(同一组件中的原生 HTML 元素)并将一些逻辑应用于这些子元素。

经过多次搜索和努力,我找到了一种使用ViewContainerRefinParentDirective@ViewChildrenin 的方法AppComponent,但我不得不使用((this.viewContainerRef as any)._view.nodes),这看起来不像是正确的方法。

有没有其他方法可以获得Child Elements父指令中的引用??

示例堆栈闪电战 在这里

随意分叉代码并根据需要进行更新。提前致谢

家长指令

export class ParentDirective {
  constructor(private vcr: ViewContainerRef) {}

  ngAfterViewInit() {
    console.log((this.vcr as any)._view.nodes);
    let lists = (this.vcr as any)._view.nodes.filter(
      x => x.constructor.name === "QueryList"
    );
    lists.forEach(list => {
      list.toArray().forEach(x => {
        if (x.constructor.name === "ChildXyzDirective")
          x.elementRef.nativeElement.style.background = "red";
        else x.elementRef.nativeElement.style.background = "green";
        console.log(x);
      }); …
Run Code Online (Sandbox Code Playgroud)

angular-directive viewchild angular

2
推荐指数
1
解决办法
2353
查看次数

升级到 Angular 9 后指令不适用于 FormControl

我已经使用指令来启用和禁用表单。这是在一个单独的打字稿文件中。代码如下: -

import { NgControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';

@Directive({
    selector: '[disableControl]'
})
export class DisableControlDirective {
    @Input('disableControl') set disableControl( condition : boolean ) {
        const action = condition ? 'disable' : 'enable';
        this.ngControl.control[action]();
    }
    constructor (private ngControl : NgControl){}
}
Run Code Online (Sandbox Code Playgroud)

HTML:-

<div class="card" *ngIf="commentsFormEnable">
    <div class="card">
      <h3 class="mb-0">
        <button class="btn  btn-primary btn-sm" aria-expanded="false">
          Comments
        </button>
      </h3>
      <form [formGroup]="commentsForm" data-target="comments" id="commentsForm" (ngSubmit)="onSubmit($event)">
        <div class="row">
          <div class="col">
            <div class="input-group mb-3">
              <div class="input-group-prepend">
                <span class="input-group-text">Comments</span>
              </div> …
Run Code Online (Sandbox Code Playgroud)

angular-directive angular angular9

2
推荐指数
1
解决办法
3090
查看次数

Angular 9 中的 *ngFor 问题,当我尝试在锚标记中使用它时,它显示“属性 ngFor 上没有匹配指令”

<a *ngFor="let recipe for recipes" href="#" class="list-group-item clearfix">
  <div class="pull left">
      <h4 class="list-group-item-heading">{{ recipe.name }}</h4>
      <p class="list-group-item-text">{{ recipe.description }}</p>
      <span class="pull-right">
          <img src="" alt="{{recipe.name}}" class="img-responsive" style="max-height: 50px"/>
      </span>
  </div>
</a>
Run Code Online (Sandbox Code Playgroud)

由于此消息,我无法在此处使用 ngFor 指令

angular-directive angular

2
推荐指数
1
解决办法
1292
查看次数

如何在 *ngFor 中的数组元素之间放置逗号?

我想知道如何在数组元素之间放置逗号,而行尾没有逗号。有类似的问题,但我的有点不同,因为我使用 *ngFor 指令来显示文本:

<span *ngFor="let style of styles">
    {{style}} //If I put a comma after the text, there would be a comma at the end of the line after the  
              //last element was displayed
<span>
Run Code Online (Sandbox Code Playgroud)

解决我的问题的方法是什么?

html javascript typescript angular-directive angular

2
推荐指数
1
解决办法
469
查看次数