2014-10-19 47 views
1

經過一番搜索,我還沒有在這個不好的實踐中找到很多信息。比方說,我有一個控制器的行爲就像是(我知道這應該是一個指令,並在控制器,我們永遠不會做DOM操作,但我很好奇..)如何調用指令如果包含指令的元素通過角度控制器動態添加?

angular.module('app').controller('test', ['$scope', 
    function($scope) { 
     $scope.addElement = function() { 

      var input = document.createElement('input'); 
      input.type = "text"; 
      //directive 
      input.setAttribute("autosize","autosize"); 
      input.setAttribute("ng-model","dummy"); 
      //[ append code ] 
      input.focus(); 



     } 
    } 
]); 

,讓我們假設我有一個按鈕觸發addElement()和ng-click。如何將現有的autosize指令「觸發」到實際工作中。相反,預先輸入並具有autosize指令的輸入元素可以正常工作。我也試過$ scope.apply(function(){});圍繞創建輸入元素,它會導致類型錯誤的縮進代碼:不確定是不是一個函數:/

+2

你試過'$ compile(input)($ scope);'? – 2014-10-19 07:21:30

+0

哇好感謝 - 我不知道有一種方法來通過控制器調用$編譯 - 我正在更新代碼 – 2014-10-19 12:22:08

回答

2

基於穆罕默德Shahrouri的評論上面,我不得不注入控制器的$compile依賴,我不得不在添加$compile(input)($scope);結束:

angular.module('app').controller('test', ['$scope','$compile', 
    function($scope, $compile) { 
     $scope.addElement = function() { 

      var input = document.createElement('input'); 
      input.type = "text"; 
      //contains directive 
      input.setAttribute("autosize","autosize"); 
      input.setAttribute("ng-model","dummy"); 
      //[ append code ] 
      input.focus(); 
      $compile(input)($scope); 

     } 
    } 
]);