加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS Transclusion Directive with ngRepeat导致混合范围

发布时间:2020-12-17 06:47:21 所属栏目:安全 来源:网络整理
导读:AngularJS有一个超级漂亮的ngTransclude指令,它用控制器模板中的html替换指令模板中的html.如果在指令中使用隔离范围,则可以使用ngTransclude从控制器范围访问变量. 当我最终看到一个看似随机的结果时,我试图这样做. ngRepeat中的ngTransclude从指令的作用域
AngularJS有一个超级漂亮的ngTransclude指令,它用控制器模板中的html替换指令模板中的html.如果在指令中使用隔离范围,则可以使用ngTransclude从控制器范围访问变量.

当我最终看到一个看似随机的结果时,我试图这样做. ngRepeat中的ngTransclude从指令的作用域返回值,而不是控制器的作用域.

关闭AngularJS文档,我创建了一个Plunker:http://plnkr.co/edit/GtrYtGoy2fnvgkwLFAGN?p=preview

JS

angular.module('docsTransclusionExample',[])
  .controller('Controller',['$scope',function($scope) {
    $scope.names = ['Tobias','Funke'];
  }])
  .directive('myDialog',function() {
    return {
      restrict: 'E',transclude: true,scope: {},templateUrl: 'my-dialog.html',link: function (scope,element) {
        scope.names = ['Jeff','Bridges'];
      }
    };
  });

的index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example87-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
  <script src="script.js"></script>



</head>
<body ng-app="docsTransclusionExample">
    <div ng-controller="Controller">
    <my-dialog>Check out the contents,{{names}}!</my-dialog>
  </div>
</body>
</html>

我-dialog.html

<div class="alert" ng-transclude></div>
<div ng-repeat="name in names">
  <div class="alert" ng-transclude></div>
  {{name}}
</div>
<div class="alert" ng-transclude></div>

此代码返回:

Check out the contents,["Tobias","Funke"]!
Check out the contents,["Jeff","Bridges"]!
Jeff
Check out the contents,"Bridges"]!
Bridges
Check out the contents,"Funke"]!

根据我读过的文档,以及我发现的用于翻译和范围的翻译和范围文章,翻译只应该考虑到控制器的范围,意思是中间的两个“查看内容,{{names}}!”应该读与外面两个相同.

进一步的实验让我将AngularJS版本从1.2.15更改为1.3.0 rc

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.1/angular.min.js"></script>

这导致正确的(据我所知)输出:

Check out the contents,"Funke"]!
Jeff
Check out the contents,"Funke"]!
Bridges
Check out the contents,"Funke"]!

有没有针对此问题的解决方法,我可以使用1.2.15或我在使用此版本时卡住了?应该是什么样的正确行为?

解决方法

从1.3.0b11的 changelog:

ngRepeat: ensure that the correct (transcluded) scope is used
(b87e5fc0)

对于ng-if也是一样的(在你的plunker中在1.2.15和1.3.0-rc.1之间切换时有相同的奇怪的不同行为).

所以正确的是使用1.3.0-rc.1.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读