【问题标题】:AngularJS - access directive scope from transclude scopeAngularJS - 从 transclude 范围访问指令范围
【发布时间】:2013-10-10 16:51:16
【问题描述】:

我有一个带有某种形式的指令。通常这就是我所需要的,但有时我需要添加更多的输入字段。所以我尝试为此使用嵌入,但它不起作用。

我创建了一个 plunker 来说明这一点:http://plnkr.co/edit/zNOK3SJFXE1PxsvUvPBQ?p=preview

Directive 是一个简单的表单,带有输入字段、transclusion 和一个帮助测试它的按钮(不重要部分省略):

scope: {
},
transclude: 'element',
template: 
  '<form name="myForm">' +
  '<input type="text" ng-model="data.inDirective"></input>' +
  '<div ng-transclude></div>' +
  '<button ng-click="showData()">show data</button>' +
  '</form>'

在这里它与嵌入一起使用:

<form-as-directive>
  <input type="text" ng-model="data.inTransclude"></input>
</form-as-directive>

我可以在嵌入中以某种方式使用指令的范围吗?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    如果您需要将转置的 html 中的控件绑定到指令的(隔离)范围,则必须使用链接函数的 transcludeFn 参数“手动”(不使用 ng-transclude)进行转置。此功能允许您更改嵌入的范围。

    scope: {
    },
    transclude: 'element',
    replace: true,
    template: 
        '<form name="myForm">' +
        '<input type="text" ng-model="data.inDirective"></input>' +
        '<div class="fields"></div>' +
        '<button ng-click="showData()">show data</button>' +
        '</form>',
    link: function (scope, elem, attrs, ctrl, transcludeFn) {
        // "scope" here is the directive's isolate scope 
        elem.find('.fields').append(transcludeFn(scope, function () {}));
    }
    

    否则,嵌入会自动绑定到父(控制器)范围的(新)子范围,以便访问该父范围的属性(通过继承)。

    【讨论】:

      【解决方案2】:

      好像$$nextSibling 是你需要的:

       scope.$$nextSibling.data.inTransclude
      

      来自here

      当嵌入和隔离范围都存在时,隔离范围 属性 $$nextSibling 将引用嵌入的范围。

      Plunk:http://plnkr.co/edit/z2Bmfx?p=preview

      【讨论】:

      • 这个答案已经过时了。在 1.3+ 版本之后,Isolated scope 是 transcluded scope 的 $parent。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      相关资源
      最近更新 更多