강좌 & 팁
글 수 2,412
2015.01.09 16:10:37 (*.134.169.166)
73604
01. Binding : http://forum.falinux.com/zbxe/index.php?document_srl=804623
02. Controller : http://forum.falinux.com/zbxe/index.php?document_srl=804950
03. controller 사이의 데이터 공유 : http://forum.falinux.com/zbxe/index.php?document_srl=805325
04. controller에 메소드 만들기 : http://forum.falinux.com/zbxe/index.php?document_srl=805915
05. Filter : http://forum.falinux.com/zbxe/index.php?document_srl=806499
06. ng-repeat와 filter의 응용 : http://forum.falinux.com/zbxe/index.php?document_srl=806788
AngularJS를 활용하면 사용자가 html tag를 만들 수도 있고, attribute 및 class에 특정 코드를 inject할 수 있습니다.
이것을 directive라고 부르는데 이에 대해서 알아보도록 하겠습니다.
public/javascripts/main.js를 수정합니다.
var firstApp = angular.module('FirstApp', []);
firstApp.factory('Data', function() {
return {message: "I'm data from a service"}
});
firstApp.factory('Sites', function() {
var Sites = {};
Sites.searchEngines = [
{
name: 'google',
url: 'http://www.google.co.kr'
},
{
name: 'yahoo',
url: 'http://www.yahoo.co.kr'
},
{
name: 'naver',
url: 'http://www.naver.com'
},
{
name: 'daum',
url: 'http://www.daum.net'
},
{
name: 'bing',
url: 'http://www.bing.com'
}
];
return Sites;
});
firstApp.filter('reverse', function() {
return function (text) {
return text.split("").reverse().join("");
}
});
firstApp.controller('FirstCtrl', function($scope, Data) {
$scope.data = Data;
});
firstApp.controller('SecondCtrl', function($scope, Data) {
$scope.data = Data;
$scope.reversedMessage = function (message) {
return message.split("").reverse().join("");
};
});
firstApp.controller('SiteCtrl', function($scope, Sites) {
$scope.sites = Sites;
});
firstApp.directive("site", function() {
return {
restrict: "E",
transclude: true,
scope: {
url: "@",
},
template: "<li ng-transclude></li><a href='{{url}}'>{{url}}</a>"
};
});
public/index.html을 수정합니다.
<!DOCTYPE html>
<html>
<head>
<title>Binding</title>
</head>
<body>
<div ng-app="FirstApp">
<div ng-controller="SiteCtrl">
<input type='text' ng-model='searchText'>
<ul ng-repeat="site in sites.searchEngines | filter:searchText">
<site url='{{site.url}}'>{{site.name}}</site>
</ul>
</div>
</div>
<script type="text/javascript" src="components/angularjs/angular.js"></script>
<script type="text/javascript" src="javascripts/main.js"></script>
</body>
</html>
<td>...</td>로 나열된 이해하기 힘든 코드보다 <site> ... </site>로 표시하니 이 부분은 site를 표시하겠구나 라고 이해할 수 있습니다. 이처럼 directive를 사용하면 html이 간결해지고 가독성이 높아집니다.


