繁体   English   中英

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

[英]Angular scope.$watch not working in directive

我有一个带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){...})

暂无
暂无

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

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