【问题标题】:Updating directive when scope variable changes in ng-grid?ng-grid中范围变量更改时更新指令?
【发布时间】:2014-09-19 17:28:38
【问题描述】:

我需要在 ng-grid 中使用一组对象,这些对象的自定义样式看起来像一个标签(类似于此处的标签)。

我采用了使用 cellTemplate 的方法,并为此创建了一个自定义指令。

发生的情况是,当您进行排序时,其他列会发生变化,但“标签”列不会,它会保持原样,就像指令没有更新一样。

这是我的指令:

app.directive('tag', function($compile){
   return {
   restrict: 'EA',
   link: function(scope, element, attrs) {
            attrs.$observe('tags', function(value) {
                var array = JSON.parse(value);
                var newHtml = '<ul>';

                for(var i=0;i<array.length;i++)
                {
                  newHtml += '<li>' + array[i].text + '</li>';
                }

                newHtml += '</ul>';

                var e = $compile(newHtml)(scope);
                element.replaceWith(e);

            });
         }
      }
 });

这里是一个笨蛋:http://plnkr.co/edit/OxeUPaLLWtiCnvmgehnl

谢谢

【问题讨论】:

    标签: angularjs ng-grid


    【解决方案1】:

    不知道这是否满足您的所有要求,但您可以将您的标签指令更改为:

    app.directive('tag', function($compile){
      var ddo = {
        restrict: 'EA',
        template: '<div><ul><li ng-repeat="tag in tags">{{tag}}</li></div>',
        scope: { tags: "=tags" }
        };
      return ddo;
    });
    

    或者如果你想保留你的代码,只需先更改 DOM,然后再编译:

    app.directive('tag', function($compile){
      var ddo = {
        restrict: 'EA',
        scope: { tags: "@tags" },
        link: function(scope, element, attrs) {
            attrs.$observe('tags', function(value) {
              var array = JSON.parse(value);
              var newHtml = '<ul>';
    
              for(var i=0;i<array.length;i++)
              {
                newHtml += '<li>' + array[i].text + '</li>';
              }
    
              newHtml += '</ul>';
    
              element.html(newHtml);
              $compile(newHtml)(scope);
    
            });
        }
      };
    
      return ddo;
    });
    

    编辑:另外,如果您只想更改布局,没有什么能阻止您在 cellTemplate 中调用 ng-repeat:

    cellTemplate: '<ul><li ng-repeat="val in row.entity.arr">{{val}}</li></ul>'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 2014-05-18
      • 2015-12-14
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多