0

Edit :

Please notice that this question is not duplicated as in this question they used $watch inside a controller, but I used it inside link function.

I've created a directive that wraps the jstree jquery plugin, as following :

(function () {
    'use strict';

    angular.module('XYZ').directive('myTree', myTreeDirective);

    myTreeDirective.$inject = ['$http', '$compile'];

    var tree = {};
    var config = {};

    function myTreeDirective($http, $compile) {
    
        function plugins(scope, element, attrs, config) {
            //some code
            return config;
        }

        function events(scope, element, attrs) {
            //some code
            return config;
        }

        function init(scope, element, attrs) {
            plugins(scope, element, attrs, config);
            tree = $(element).jstree(config);
            events(scope, element, attrs);
        }

        /*
         * Link function
         */
        function linkFn(scope, element, attrs) {
            $(function () {
                config.core = {};
                if (attrs.treeCore) {
                    config.core = $.extend(config.core, scope[attrs.treeCore]);
                }

                if (attrs.treeData === 'scope') {
                    scope.$watch('ngModel', function (n, o) {
                        if (n) {
                            config.core.data = scope.ngModel;
                            $(element).jstree('destroy');
                            init(scope, element, attrs, config);
                        }
                    }, true);
                }
            });
        }
        
        // expose directive
        return {
            restrict: 'E',
            link: linkFn,
            scope: {
                ngModel: "=",
                treeTypes: "=treeTypes"
            }
        };
    }
})();

And since I'm preparing my application for Angular 2 migration I'm looking for an alternative for the $watch function :

scope.$watch('ngModel', function (n, o) {
    if (n) {
        config.core.data = scope.ngModel;
        $(element).jstree('destroy');
        init(scope, element, attrs, config);
    }
}, true);

I thought about using Object.defineProperty but this is used to define a property, and what I'm doing is to execute a code when the ngModel value is changed.

From a google search I found that I can use $onChanges and $doCheck Life-cycle Hook, but I don't know how to use them to replace the code above.

Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

1 Answers1

0

Since you're preparing for angular2, then I would say that ES6 classes are an option. With ES6 classes you can define a setter function for your property.

Mike Feltman
  • 5,160
  • 1
  • 17
  • 38