简体   繁体   中英

Angular scope.$watch not working in directive

I have an angular directive with a scope.$watch which is not working, but I know the value is changing. Here's the directive:

   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);
                                    }
                            );
                };
            }
        };
    };

Here's the tag:

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

I know the currentContext.currentStep is changing, because I also have this on my page and it updates:

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

The alert gets called the first time, but then when the value changes (evidenced by the bit in the pre tags) the alert does not get called again and I have no js console errors.

The output for the step (it's data type) is:

{
  "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"
      }
    ]
  ...

Try to use $watch method with third argument set by true ( objectEquality ):

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

Or use $watchCollection :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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