【问题标题】:Directive not recognizing passed in variable指令不识别传入的变量
【发布时间】:2018-11-24 12:26:38
【问题描述】:

我有一个在事件广播后显示的指令。在处理事件时,我设置了需要传递给指令的变量。但在范围内它始终是未定义的。我包括了我也在使用的“配置文件”变量,它被正确设置为调用控制器的一部分。呈现指令时,它已填充配置文件但未填充供应商,即使“on”事件已运行并将步骤编号设置为 3 并具有有效 Id。好困惑

我的 HTML 代码

<div ng-if="oc.stepNumber == 3">
    <store-Menu profile="oc.selectedProfile" vendorId="oc.selectedVendor" />
</div>

我的指令(简体)

export class StoreMenuDirective implements ng.IDirective {
     templateUrl = 'app/_customer/orderingV2/storeMenu/storeMenu.html';
     scope = {
         profile: '=',
         vendorId: '='
      };
      controller = StoreMenuController;
      controllerAs = 'smc';
  }

各自的控制器:

    constructor(private $scope: any) {

         alert('VendorId in SMC: ' + $scope.vendorId); --Always undefined
         this.profile = $scope.profile;   --Always Set
    }

调用控制器

     $scope.$on('orderMenuSelected', angular.bind(this, (event: any, data: any) => {
        this.selectedVendor = data.vendorId;
        alert('VendorId in OC: ' + data.vendorId);  //is Set here correctly.

        //directive is rendered here, but the vendor id never makes it
        this.stepNumber = 3;
    }));

【问题讨论】:

  • 你尝试过使用 var smc = this;然后使用 alert('VendorId in SMC: ' + smc.vendorId);

标签: angularjs typescript angularjs-directive angularjs-scope


【解决方案1】:

AngularJS 规范化元素的标签和属性名称。 HTML 不区分大小写,因此,AngularJS 以小写形式引用 DOM 中的指令,通常在 DOM 元素上使用破折号分隔的属性(例如 ng-model)。

归一化过程如下:

  1. 从元素/属性的前面去除x-data-
  2. :-_ 分隔的名称转换为驼峰式。

话虽如此,vendorId 的 HTML 属性应该如下所示

vendor-id="oc.selectedVendor"

希望对你有帮助

【讨论】:

  • 是的,我是个白痴。自从我不得不在这个项目上做真正的工作已经有大约 2 年了,完全忘记了整个小写的事情。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2021-02-16
  • 2017-02-24
  • 2017-06-11
  • 2015-03-03
  • 1970-01-01
  • 2016-08-30
相关资源
最近更新 更多