본문 바로가기
JavaScript & TypeScript

Style과 Class지정

by 향로 (기억보단 기록을) 2015. 1. 31.
반응형

예를들어 어떤 메뉴들을 조건에 따라 활성/비활성화하려면 코드를 다음과 같이 작성할 수 있다.

home.jsp

<style>

.disabled-true {

color:gray;

}

</style>

<body ng-app="app"  ng-controller="MainCtrl">

<ul>

<li class='disabled-{{isDisabled}}' ng-click='stun()'>기절시키다</li>

</ul>

</body>



home.js

var app = angular.module('app', []);


app.controller('MainCtrl', function($scope){

$scope.isDisabled = false;

$scope.stun = function(){

$scope.isDisabled = 'true';

};

});


처음 isDisabled의 경우 false 이므로 '기절시키다' text에는 아무런 변화가 없다. 그러나 해당 text를 클릭시에는 

지정해놓은 style인 gray 색으로 변할 것이다.

즉, style="{{표현식}}" 같은 형태로 인터폴레이션( '{{표현식}}' 을 인터폴레이션이라 한다.) 과 

인라인 스타일을 병용해도 된다는 말이다.

이 방법은 기발하긴 하지만, 

조금만 복잡해져도 템플릿과 스크립트를 이해하고 CSS를 그에 맞게 작성하기가 매우 힘들어 진다.


Angular에는 이를 해결하기 위해 ng-class와 ng-style라는 지시어가 있다.

이를 활용하면 home.jsp 코드가 아주 직관적으로 바뀐다.


home.jsp

<style>

.disabled{

color:gray;

}

</style>

<body ng-app="app"  ng-controller="MainCtrl">

<ul>

  <li ng-class='{disabled: isDisabled}' ng-click='stun()'>기절시키다</li>

</ul>

</body>


코드 그대로 해석하면 된다.

disabled 라는 class는 isDisabled가 true이면 class속성에 추가하고, false라면 추가하지 않겠다는 말이다.

즉, {class명: boolean 타입} 으로 작성하여 우측에 있는 값이 true일 경우 해당 class를 추가,

false일 경우 추가하지 않겠다는 것이다.


좀 더 응용해서 list에서 클릭한 곳에 형광펜 효과를 주는 기능을 구현해보자.

home.jsp

  .selected {

background-color : lightgreen;

}

<body ng-app="app"  ng-controller="MainCtrl">

<table>

<tr ng-repeat='restaurant in directory' ng-click = 'selectRestaurant($index)' ng-class='{selected: $index == selectedRow}'>

<td> {{restaurant.name}}</td>

<td> {{restaurant.cuisine}}</td>

</tr>

</table>

</body>

directory에 있는 객체들을 restaurant 라는 임시객체에 담아서 반복적으로 tr을 생성한다. 

해당 row 클릭시에는 selectRestaurant() 를 호출하되 parameter값으로 row의 index를 넘기고, index가 selectRow의 값과 같은 경우에는 selected class를 추가한다.

 

home.js

var app = angular.module('app', []);


app.controller('MainCtrl', function($scope){

$scope.directory = [{name:'암소구이', cuisine:'바베큐'},

                   {name:'청정 샐러드', cuisine:'샐러드'},

                   {name:'피시하우스', cuisine:'해산물'}];

$scope.selectRestaurant = function(row){

$scope.selectedRow = row;

};

});



반응형