
강좌 & 팁
글 수 2,412
2014.11.28 14:40:21 (*.134.169.166)
71893
지난 글(http://forum.falinux.com/zbxe/index.php?document_srl=804623&mid=lecture_tip)에 이어서 컨트롤러에 대해서 알아보도록 하겠습니다.
컨트롤러는 바인딩을 하기 전에 필요한 비즈니스 로직을 구현하는 곳입니다.
우선 지난 글에서 만든 public/index.html을 아래와 같이 수정해보겠습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html> < html > < head > < title >Binding</ title > </ head > < body > < div ng-app = "FirstApp" > < div ng-controller = "FirstCtrl" > < input type = "text" ng-model = "data.message" > < h1 >{{data.message}}</ h1 > </ div > </ div > < script type = "text/javascript" src = "components/angularjs/angular.js" ></ script > < script type = "text/javascript" src = "javascripts/main.js" ></ script > </ body > </ html > |
그리고 public/javascripts/main.js를 아래와 같이 작성합니다.
1 2 3 4 | var firstApp = angular.module( 'FirstApp' , []); firstApp.controller( 'FirstCtrl' , function ($scope) { $scope.data = {message: "Hello" }; }); |
브라우저를 열어서 확인해보면 Hello라고 기본값이 입력이 되어있을 것입니다.
$scope는 AngularJS가 dependency injection을 통해서 넣어주는 인자입니다. 이 $scope는 해당 controller안에서만 유의미하다는 점을 유념해야겠습니다.
다음과 같이 public/index.html 및 public/javascripts/main.js를 수정해서 scope에 대해서 확인해봅시다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html> < html > < head > < title >Binding</ title > </ head > < body > < div ng-app = "FirstApp" > < div ng-controller = "FirstCtrl" > < input type = "text" ng-model = "data.message" > < h1 >{{data.message}}</ h1 > </ div > < div ng-controller = "SecondCtrl" > < input type = "text" ng-model = "data.message" > < h1 >{{data.message}}</ h1 > </ div > </ div > < script type = "text/javascript" src = "components/angularjs/angular.js" ></ script > < script type = "text/javascript" src = "javascripts/main.js" ></ script > </ body > </ html > |
1 2 3 4 5 6 7 | var firstApp = angular.module( 'FirstApp' , []); firstApp.controller( 'FirstCtrl' , function ($scope) { $scope.data = {message: "Hello First" }; }); firstApp.controller( 'SecondCtrl' , function ($scope) { $scope.data = {message: "Hello Second" }; }); |
브라우저로 확인하면 첫번째 항목에는 Hello First, 두번째 항목에는 Hello Second가 표시됩니다. 이와 같이 같은 data.message를 사용했지만 서로 다른 controller에서는 각각의 $scope에 해당하는 값들이 표시됩니다.
이상으로 controller에 대해서 알아보았습니다.