2014-10-19 89 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); 

     } 
    } 
]);