【问题标题】:angularjs - access transclude html scope from hosting directiveangularjs - 从托管指令访问 transclude html 范围
【发布时间】:2017-08-08 12:13:14
【问题描述】:

我有一个带有嵌入 html 的简单指令。 我希望能够将指令范围参数注入到 transclude。 我在 plunker 中写了一个简单的例子: https://plnkr.co/edit/jqyiQdgQxbeTrzyidZYF?p=preview

我知道在 angular 4 中可以做到,但我找不到在 angularjs 中做到这一点的好方法。

// Code goes here

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

app.controller("mainCtrl", function($scope) {
  $scope.users = ["tal", "oren", "orel", "shluki"];
  
  $scope.deleteUser = (user) => {alert("trying to delete", user);}
});

app.directive('myList', function myList() {
    return {
        restrict: 'E',
        transclude: true,  
        template: "<div><table><tr ng-repeat='item in collection'><td> This is inside myList - user name: {{item}} <ng-transclude></ng-transclude></td></tr></table></div>",
        scope: {
          collection: "="
        },
        replace: true
    };
});
<!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="app" ng-controller="mainCtrl">
      <h1>Hello Plunker!</h1>
      <my-list collection="users">
         <h2>This is transclude</h2>
         <button ng-click="deleteUser(user)">Delete user: {{user ? user : "User name should be here"}}</button>
      </my-list>
  </body>

</html>

真的会得到一些帮助。

plunker:https://plnkr.co/edit/jqyiQdgQxbeTrzyidZYF?p=preview

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    这是一个与您的示例一起工作的 plunker。 http://plnkr.co/edit/BjSowyQdLXd0xoCZFqZ6?p=preview

    我们的想法是将它作为内容而不是 html 作为字符串传递。 $compile 在这里是因为链接是在 ng-repeats 已经嵌入了它自己的模板之后完成的。

    var template = '<h1>I am foo</h1>\
                      <div ng-repeat="item in users">\
                        <placeholder></placeholder>\
                        <hr>\
                      </div>';
      var templateEl = angular.element(template);
    
      transclude(scope, function(clonedContent) {
        templateEl.find("placeholder").replaceWith(clonedContent);
    
        $compile(templateEl)(scope, function(clonedTemplate) {
          element.append(clonedTemplate);
        });
      });
    

    如果您想正确解释问题所在,您应该在此处查看详细答案:Pass data to transcluded element

    希望对你有所帮助

    【讨论】:

    • 首先非常感谢您的帮助。一开始我很认真,但唯一的问题是我失去了容器范围。如果我尝试从主页访问一些数据,我就不能再这样做了。您在我的示例中实现的解决方案不会调用 deleteUser 函数,因为范围已被替换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多