AngularJS创建一个指令,然后使用另一个指令

AngularJS creating a directive then uses another directive

本文关键字:指令 然后 另一个 一个 创建 AngularJS      更新时间:2023-09-26

我正在尝试创建一个指令,以减少我必须编写的样板代码。

我使用angular的xeditable指令来允许内联编辑,但是当我从我的指令中添加xeditable指令属性时,它不起作用。

当我说它不起作用时,我的意思是通常当我点击元素时,会出现一个输入框,而现在当我点击元素时什么也没发生。

Glenn.directive('edit', function() {
    return {
        restrict: 'A',
        template: '{{ content.' + 'ParamData' + '.data }}',
        scope: {
            ParamData: '@edit'
        },
        link: function(scope, element, attrs) {     
            element.attr('editable-text', 'content.' + attrs.edit + '.data');
            element.attr('onbeforesave', 'update($data, content.' + attrs.edit +'.id');
        }
    }
});

所以,我的第一个问题是,xeditable指令不工作,因为它在我的内部。我是创建angularjs指令的新手,但我想知道它是否可以与其编译的方式有关?

我的第二个问题是模板。如果我的模板是这样的

template: '{{ ParamData }}'

然后它输出正确的数据,但是如果没有其他部分引用范围数据,我就无法使它工作。

还有,下面是使用

指令时视图的样子
<h2 edit="portrait_description_title"></h2>

如果我没有使用指令来减少锅炉代码

<h1 editable-text="content.portrait_description_title.data" onbeforesave="update($data, content.portrait_description_title.id)">
     {{ content.portrait_description_title.data }}
</h1>

谢谢你的建议!

您必须在添加这些属性后重新编译元素,下面是一个示例:

示例柱塞: http://plnkr.co/edit/00Lb4A9rVSZuZjkNyn2o?p=preview

.directive('edit', function($compile) {
  return {
    restrict: 'A',
    priority: 1000,
    terminal: true, // only compile this directive at first, will compile others later in link function
    template: function (tElement, tAttrs) {
      return '{{ content.' + tAttrs.edit + '.data }}';
    },
    link: function(scope, element, attrs) {
      attrs.$set('editable-text', 'content.' + attrs.edit + '.data');
      attrs.$set('onbeforesave', 'update($data, content.' + attrs.edit + '.id)');
      attrs.$set('edit', null); // remove self to avoid recursion.
      $compile(element)(scope);
    }
  }
});

注意事项:

  • 删除孤立的作用域以简化事情,因为似乎您想首先直接绑定到控制器content.portrait_description_title.data中的作用域。
  • template:也接受函数,这样可以得到edit属性值来构造模板。
  • 标记为terminal指令并引发priority,这样在第一次运行时,只有这个指令(在同一元素中的其他指令之外)将被编译。
  • attrs.$set()用于添加/删除属性,使用它添加editable-text指令和onbeforesave
  • 删除指令本身,即edit属性,以防止下一次编译后的递归。
  • 使用$compile服务重新编译元素,以使editable-textonbeforesave工作

只需在第一个指令的模板中添加另一个指令,并将其绑定到您从attr中获得的作用域模型。您还可以添加控制器功能,并创建更多的模型,或逻辑和绑定到指令模板。

也可能你的属性在模板上不可用,那么你需要在你的隔离作用域模型中添加$watch,并在控制器中更新另一个作用域模型。第二个模型需要绑定到模板。关于指令的更多信息你可以在AngularJS文档中找到,这里有一篇很好的文章,它可以帮助你:

http://www.sitepoint.com/practical-guide-angularjs-directives-part-two/