首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义编译函数移除双向绑定。

自定义编译函数移除双向绑定。
EN

Stack Overflow用户
提问于 2016-11-09 15:44:40
回答 1查看 85关注 0票数 2

我的角1.5.8应用程序中有一个属性指令my-directive。我想将它添加到一个元素中,并且我还想传递两个额外的参数,一个是one-way绑定(@),另一个是two-way绑定(=)。

它可以正常工作,直到我尝试自定义指令的编译函数以添加额外的属性。one-way绑定仍然工作正常,但是two-way绑定就消失了。

这是扑通

如果我注释掉编译函数,它将再次工作。我想我是在以某种方式覆盖默认行为,但我想不出如何防止这种情况发生。

我的编译功能:

代码语言:javascript
复制
compile: function compile(element, attrs) {
  return {
    pre: function preLink(scope, iElement, iAttrs, controller) {},
    post: function postLink(scope, iElement, iAttrs, controller) {
      if (!iAttrs.compiled) {
        iElement.attr('compiled', true);
        iElement.attr('ng-click', "$ctrl.onClick()");
        $compile(iElement)(scope);
      }
    }
  };
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-09 16:37:01

对于为什么会出现这种情况,我没有确切的答案,但是编译只适用于当前集合中的子元素。因此,您只需将$compile(...更改为以下代码即可解决此问题。

代码语言:javascript
复制
$compile(iElement.children())(scope);

更新1

显然,iElement的作用域已经由父作用域定义。因此,编译将无法使用该元素,因为孤立的作用域仅在指令中工作。

但是,现在的问题是如何在编译阶段添加新的指令?可以通过将指令更改为以下代码来做到这一点:

代码语言:javascript
复制
.directive('myDirective', function($compile) {
    return {
      terminal: true,
      priority: 1001,
      restrict: 'A',
      scope: {
        myObject: '=myObject',
        text: '@text'
      },
      transclude: true,
      bindToController: true,
      controller: function() {
        var $ctrl = this;
        $ctrl.onClick = onClick;
        return $ctrl;

        function onClick() {
          alert("clicked");
        }
      },
      controllerAs: '$ctrl',
      template: '<pre>{{$ctrl}}</pre> {{ $ctrl.text }} - {{ $ctrl.myObject.attr1 }}',
      compile: function compile(element, attrs) {
        element.removeAttr("my-directive");
        element.attr('compiled', true);
        element.attr('ng-click', "$ctrl.onClick()");
        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {},
          post: function postLink(scope, iElement, iAttrs, controller) {
            $compile(iElement)(scope);
          }
        };
      }
    };
  });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40510845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档