如何将范围绑定到从指令动态添加的html?

时间:2016-04-25 19:25:59

标签: angularjs-directive

下面是简单的脚本,当我重复范围变量名称并使用指令 usescope 时,我需要的功能就是当我们点击名称时应该添加** Hello name **,但是我无法&# 39; t绑定范围。有人可以帮忙吗?

<!DOCTYPE html>
<html>
  <body>
    <div ng-app="app" ng-controller="test">
      <table>
        <tr ng-repeat="name in names track by $index"> 
            <td data-usescope=""> {{name}} </td>
        </tr>
      </table>
    </div>
    <script   
      src="https://code.jquery.com/jquery-2.2.3.min.js"   
      integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   
      crossorigin="anonymous">
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script type="text/javascript">
      var app = angular.module('app', []);

      app.controller('test', function($scope) {
        $scope.names = ["Test1","Test2"];
      });

      app.directive('usescope',
        function ($compile) {
          return {
            link: function (scope, element, attrs) {
                element.click(function(e) {
                    e.preventDefault();
                    element.append($compile('<span> Hello {{name}} </span>')(scope));
                });
            }
        };
      });

    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

我建议遵循解决方案。可以在 - @sumit Plunker找到一个工作示例。这是一个代码示例:

<body ng-controller="test">
  <div>
    <table>
      <tr ng-repeat="name in names track by $index">
        <td data-usescope="name"> {{name}} </td>
      </tr>
    </table>
  </div>
</body>

app.directive('usescope',
  function($compile) {
    return {
      scope: {
        'name': '=usescope'
      },
      link: function(scope, element, attrs) {
        element.click(function(e) {
          e.preventDefault();
          var compiledeHTML = $compile("<span id='span1'> Hello " + scope.name + "</span>")(scope);
          element.append(compiledeHTML);
        });
      }
    };
  });