2016-05-25 32 views
0

我是新的angularjs,我有代碼點擊'按鈕'一個新行插入一個'新按鈕',現在輪到'新按鈕'還應該有ng-click事件。問題是,當我嘗試這樣做時,帶有新按鈕的動態行被添加,但新按鈕沒有獲取附加到它的點擊事件。經過一番研究後,我發現我應該在添加到DOM之前編譯元素字符串,其幫助文件爲「$ compile」 angularjs的服務。但然後瀏覽器拋出錯誤說,'$編譯器不是一個函數' ...請幫助。謝謝..!! 以下是代碼片段 jsp頁面代碼數據ng單擊事件綁定到DOM

<td> 
     <button type="button" id="clickButton" data-ng-click="insert()" 
       class="btn btn-sm btn-default"> 
       <i class="fa fa-plus fa-lg"></i> 
     </button> 
    </td> 

angularjs控制器代碼

$scope.insert = function($compile){ 
      var tableRow ="<tr data-ng-repeat='c in ctrl.client.clientOwnerVOList' id='insertionRow"+count+"'>"+ 
       "<td>"+i+"</td>"+ 
       "<td class='col-lg-3'><input type='Text' class='form-control' data-ng-model='c.clientOwnerName' name='clientOwnerName{{$index + 1}}' id='Name'></td>"+ 
       "<td class='col-lg-4'><input type='Email' class='form-control' data-ng-model='c.clientOwnerEmail' name='clientOwnerEmail{{$index + 1}}' id='Email'></td>"+ 
       "<td class='col-lg-3'><input type='Text' class='form-control' data-ng-model='c.clientOwnerPhone' name='clientOwnerPhone{{$index + 1}}' id='PhoneNo'></td>"+ 
       "<td><button type='button' data-ng-click=insert() class='btn btn-sm btn-default'><i class='fa fa-plus fa-lg'></i></button></td>"+ 
       "<td><button type='button' class='btn btn-sm btn-default' onClick=$(this).closest('tr').remove();><i class='fa fa-trash fa-lg '></i></button></td>"+ 
       "</tr>"; 
       var newTableRow = $compile(tableRow)($scope); 
       $("#insertionRow").append(newTableRow); 
       i++; 
      }; 

回答

0

您可以創建一個使用編譯指令:

app.directive('dynamic', [ '$compile', 
function ($compile) { 
    return { 
     restrict: 'A', 
     replace: true, 
     link: function (scope, ele, attrs) { 
      scope.$watch(attrs.dynamic, function (html) { 
       ele.html(html); 
       $compile(ele.contents())(scope); 
      }); 
     } 
    }; 
}]); 

然後在您的html:

<div dynamic="tableRow"></div> 

...無論你想錶行顯示。

0

爲什麼你傳遞$編譯爲函數的參數嗎?你應該注入$編譯服務,就像你注入$範圍,即在你的控制器/指令中。

這可能是原因,它是拋出$ compile不是函數錯誤。