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

时间:2016-02-08 15:33:36

标签: javascript angularjs

我有一个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"
      }
    ]
  ...

1 个答案:

答案 0 :(得分:0)

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

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

或使用$watchCollection

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