2017-08-03 52 views
0

编辑:

请注意,这个问题是不重复在此question他们用$观看控制器内,但我用它连接功能里面。

我已经创建了一个包装jstree jQuery插件指令,如下:

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

而且,由于我准备我的角2移民申请我正在寻找一个替代的$watch功能:

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

我想过使用Object.defineProperty但是这是用来定义一个属性,我在做什么是当ngModel值改变为执行代码。

从谷歌搜索我发现我可以使用$onChanges$doCheck生命周期钩,但我不知道如何使用它们来替换上面的代码。

回答

0

既然你正在准备angular2,那么我会说ES6类是一个选项。有了ES6类,你可以为你的财产定义一个setter函数。

相关问题