Change directive when changing scope variable

I am using an http request to retrieve data from a json file that I use in the controller.

    app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) {
   //gets data from service 
        loaderService.getLoadedHtml().then(function (result) {
            $scope.fields = result.data;
        });
    }]);

I need to update the directive when this $scope.fieldschanges as

app.directive('dform', function () {
    return {
        scope: {
            action: '@',
            method: '@',
            html: '='
        },
        link: function (scope, elm, attrs) {
            var config = {
                "html": scope.fields
            };

            scope.$watch('fields', function (val) {
                elm.dform(config);
            });

            //console.log(config);
            //elm.dform(config);
        }
    };
})

and this is how i use this directive

<div html="fields" dform></div>

But in my case, when the variables $ scope.fields change, I get scopeundefined in my $ watch function.

Question:

How to get updated value for scope.fields in a scope. $ watch function?

+4
source share
3 answers

You need to provide directory access to fieldsby adding a binding for it:

scope: {
  action: '@',
  method: '@',
  html: '=',
  fields: '='
}

And HTML:

<dform fields="fields" ...

undefined , dform:

scope.$watch('fields', function(newValue, oldValue) {

  if (newValue === oldValue) return;

  var config = {
    "html": newValue
  };

  elm.dform(config);
});

Update

HTML:

<div html="fields" dform></div>

html , $parent fields :

scope.$watch('html', ...
+2

, , . .

,

scope: false,
link: function (scope, elm, attrs) {
    scope.$watch(function () { return scope[attrs.html] }, function (val) {
        if (val === undefined) return;

        var config = {
            action: attrs.action,
            method: attrs.method,
            html: val
        };

        elm.dform(config);
    });

}

, bindToController , ( , html, $scope.$watch self.$onChanges hook).

scope: true,
bindToController: {
    action: '@',
    method: '@',
    html: '='
},
controller: function ($scope, $element) {
    var self = this;

    $scope.$watch(function () { return self.html }, function (val) {
        if (val === undefined) return;

        var config = {
            action: attrs.action,
            method: attrs.method,
            html: val
        };

        $element.dform(config);
    });
}

, html="fields", scope fields.

+1

use $parent.fieldsinsteadfields

0
source

Source: https://habr.com/ru/post/1664908/


All Articles