AngularJS 동적 HTML, Function 추가

■ AngularJS에서 동적으로 HTML코드를 추가하고 추가된 코드에 함수를 붙여야 할 경우가 있다. jQuery와 AngularJS를 이용하여 알아본다.

■ 코드설명

  • 6,7라인에서 jQuery와 AngularJS라이브러리를 등록한다.
  • 10라인 : $scope, $compile서비스를 등록한다.
  • 14라인 : 동적으로 생성되는 HTML코드이다.
  • 24라인 : #dynamicHtml에 $scope.RESULT 값을 동적으로 붙여준다.
  • 25f라인 : 동적으로 추가된 HTML에서 clickButton()함수는 AngularJS가 인식을 못하는데 인식할 수 있도록 $compile서비스를 이용한다.
<html>
<head>
    <title></title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('myCtrl', function ($scope, $compile) {
    
    $scope.dynamicHtml = function () {
    	
        $scope.RESULT = 
			'<table border="1">' +
			'<tr>' +
			'	<td><input type="button" ng-click="clickButton()" value="동적버튼 Action"></td>' +
			'</tr>' +
			'<tr>' +
			'	<td id="message">message...</td>' +
			'</tr>' +
			'</table>';

		angular.element("#dynamicHtml").html($scope.RESULT);
		$compile(angular.element("#dynamicHtml").contents())($scope);
    }

    $scope.clickButton = function () {
    	$("#message").append("<br/>button clicked...");
    }
});
</script>

<div ng-app="MyApp" ng-controller="myCtrl">
    <br />
    <div id="dynamicHtml">동적 HTML등록 및 action 추가</div>
    <br />
    <input type="button" value="Dynamic Html append" ng-click="dynamicHtml()" />
</div>

</body>
</html>