角度范围.$watch在指令中不起作用

Angular scope.$watch not working in directive

本文关键字:指令 不起作用 watch 范围      更新时间:2023-09-26

我有一个带有scope.$watch的角度指令不起作用,但我知道值正在发生变化。 这是指令:

   var StepFormDirective = function ($timeout, $sce, dataFactory) {
        return {
            replace: false,
            restrict: 'AE',
            scope: {
                currentStep: "=",
                title: "="
            },
            template: '<h3>{{title}}</h3><form class="step-form"></form>',
            compile: function (tElem, attrs) {
                return function (scope, elem, attrs) {
                    scope
                            .$watch(
                                    function(){return scope.currentStep;},
                                    function (newValue) {
                                        var stepFormFields = Array();
                                        stepFormFields.push($sce.trustAsHtml("<p>Fields</p>"));
                                        alert(scope.currentStep);
                                    }
                            );
                };
            }
        };
    };

这是标签:

<div title="'test'" currentStep="currentContext.currentStep"></div>

我知道currentContext.currentStep正在发生变化,因为我的页面上也有这个并且它会更新:

<pre>{{currentContext.currentStep | json}}</pre>

警报在第一次被调用,但是当值更改时(由 pre 标记中的位证明),警报不会再次调用,并且我没有 js 控制台错误。

步骤的输出(数据类型)为:

{
  "identifier": "830abacc-5f88-4f9a-a368-d8184adae70d",
  "name": "Test 1",
  "action": {
    "name": "Approval",
    "description": "Approve",
    "instructions": "Select 'Approved' or 'Denied'",
    "validOutcomes": [
      {
        "outcome": "Approved",
        "display": "Approved",
        "id": "Approved"
      },
      {
        "outcome": "Denied",
        "display": "Denied",
        "id": "Denied"
      }
    ]
  ...

尝试使用$watch方法,第三个参数由 true ( objectEquality 设置):

$watch('currentStep', function(newValue){...}, true);

或使用$watchCollection

$watchCollection('currentStep', function(newValue){...})