【问题标题】:Using a directive's compile function with an isolate scope seems to access the wrong scope使用带有隔离作用域的指令的编译函数似乎访问了错误的作用域
【发布时间】:2013-12-03 06:08:16
【问题描述】:

我不确定这是 angularjs 错误还是我做错了什么,但是当我使用隔离作用域和编译函数创建指令以以编程方式修改模板时,使用了错误的作用域。有趣的是,如果我将 ng-repeat 更改为 item in users,这应该不起作用,因为我使用的是隔离作用域......它确实有效。更令人困惑...此代码实际上在 Angular 1.1.3 中可以正常工作。有谁知道怎么回事?

小提琴:

不适用于 Angular 1.2.3 - http://jsbin.com/iPIbubA/12/edit

按原样在 Angular 1.1.3 中工作 - http://jsbin.com/iPIbubA/7/edit

在 Angular 1.2.3 中使用“用户中的项目”http://jsbin.com/iPIbubA/15/edit

例如:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Demo Blog</title>
</head>
<body>
  <div ng-app="app" class="container">
    <h1>Blog Demo</h1>
    <div class="row" ng-controller="main">
      <collection items="users">
        {{ $index + 1 }} - {{ item.name}} / {{ item.email }}
      </collection>
    </div>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>  
</body>
</html>


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

app.controller("main", function($scope) {

  $scope.users = [
    { name : "bob", email : "bob@aol.com" },
    { name : "joe", email : "joe@aol.com" }
  ];

});

app.directive("collection", function() {

  return {
    restrict : "E",

    scope : {
      "items" : "="
    },

    compile : function(el, attrs) {
      var itemTemplate = el.text();
      // if I change ng-repeat to "item in users" it works!
      el.html('<ul><li ng-repeat="item in items">' + itemTemplate + '</li></ul>');
    }

  };

});

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

使用transclude:

app.directive("collection", function() {
    return {
        restrict : "E",
        scope : {
            "items" : "="
        },
        template : '<ul><li ng-repeat="item in items">
        <span ng-transclude></span></li></ul>',
        transclude : true
    };
});

【讨论】:

  • 酷!因此,包含该内容不使用未定义项目的父范围?我认为这就是嵌入的全部意义所在?
  • 嵌入的内容确实可以访问外部范围:docs.angularjs.org/guide/directive
  • 但是在这个例子中它也可以访问隔离范围吗?因为项目只在这里定义?
  • 是的。 $indexitem 仅在指令范围内可用。因此,嵌入使用该范围。
  • 这看起来是改变这种行为的提交:github.com/angular/angular.js/commit/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多