2016-04-25 46 views
0

下面是我重複範圍變量名稱和使用指令usescope的簡單腳本,我需要的功能是當我們點擊名稱時應該添加** Hello name **,但是我無法綁定範圍。有人可以幫忙嗎?如何將範圍綁定爲從指令動態添加html?

<!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> 

回答

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); 
     }); 
     } 
    }; 
    }); 
相關問題