繁体   English   中英

带有隔离HTML的指令隔离范围

[英]Directive isolated scope with transcluded HTML

我遇到了一些与孤立范围有关的问题。 我有一个需要在许多地方使用的指令,它的控制器为该指令提供了一些辅助功能。 该指令的确创建了隔离范围,但模板引用了父范围。 下面是演示该问题的一个小贴士

http://plnkr.co/edit/LQnlSjMHeatMkmkYZyfk

$scope.text = "test"; 

旨在演示该属性在隔离范围内没有更改,并引用了父范围。 由于这个问题,我无法为每个隔离的范围调用辅助函数。 我希望我能够正确地描述我的问题。

下面是代码

HTML:

<body ng-controller="MainCtrl">
        <div transfer-box style="">
            {{text}}
        <div ng-if="refresh" ></div>
            {{refresh}}
        </div>
    <div transfer-box style="">
            {{text}}
        <div ng-if="refresh" ></div>
            {{refresh}}
        </div>
  </body>

使用Javascript:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.text = 'World';
  console.log("parent scope id "+ $scope.$id); 
});
app.directive('transferBox', function() {
      return {
        restrict: 'EA',
        xreplace: true,
        transclude: true,
        scope:true,
        template: '<div class="container-fluid" style="height:100%" ng-transclude></div>',
        controller:'transferBoxCtrl'
      };
    })
app.controller('transferBoxCtrl',['$scope',function($scope){
  console.log($scope.$id);
        $scope.refresh = true;
        $scope.text = "test";
    }])

您尚未创建隔离范围。 您需要像这样将对象传递给scope属性:

app.directive('transferBox', function() {

  return {
    restrict: 'EA',
      xreplace: true,
    transclude: true,

    // create an isolate scope
      scope:{
        text: '=?'
      },

    template: '<h1>{{text}}</div>',

      // define directive controller within the directive definition
      controller: function($scope){
         $scope.text = $scope.text || 'default'
      }

  };



});

的index.html

<body ng-controller="MainCtrl">

      <div transfer-box text="text" ></div>
      <div transfer-box ></div>

  </body>

还要注意,控制器是在指令定义中定义的,因此不需要对app.controller()任何调用。

阅读有关“指令定义对象”的文档 ,以获取有关如何定义隔离范围的更多详细信息。

DEMO-显示代码的修改版本,显示如何实现指令与父控制器之间共享的隔离范围。

这是不可能的,因为首先是角负荷子级,这里的transfer-box指令是子级,然后是父级的MainCtrl控制器。

因此,子变量始终被父变量替换。

Matt Herbstritt提供的解决方案很棒。

谢谢

问题在于嵌入的HTML。 我找到了一个链接,其中包含与我所面临的问题完全相同的描述。 我会尝试一下,只是将其发布以供其他参考。

http://angular-tips.com/blog/2014/03/transclusion-and-scopes/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM