mikeb February 2016

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": [
      {
          

Answers


Enver Dzhaparoff February 2016

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

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

Or use $watchCollection:

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

Post Status

Asked in February 2016
Viewed 1,274 times
Voted 5
Answered 1 times

Search




Leave an answer