【備忘録】AngularJSのfunction内で指定箇所にng-* 属性付きDOM要素を挿入
普通にjavascirptjsと同じようにするとDOM要素は挿入できますが、ng-* 属性は動作しないので一工夫が必要。
<script>
// モジュール定義 (ng-app="example")
angular.module('example', [])
// コントローラ定義
.controller('ExampleController', ['$scope', '$compile', function ($scope, $compile) {
$scope.addElement = function(){
// DOM追加したいDOMの生成
var el = angular.element('<button ng-click="newElement()">ボタン</button>');
// ng-* の反映
$compile(el)($scope);
// 要素の追加
angular.element($("#add")).append(el);
};
}]);
</script>
結構忘れがちなのはコントローラの定義で「'$compile'」を忘れること。