Web/Angular1

[Angular1] ng-style을 이용해 동적으로 CSS 생성하기

Binceline 2016. 12. 16. 20:16

예를 들면, 리스트 항목이 처음엔 5개라서 가로길이를 20%로 지정했는데, 


항목이 하나 늘어났다.


그럴 경우, CSS 코드를 수정해야 하겠지만


Angular의 ng-style을 이용하면 간단히 해결할 수 있다.


다음 코드를 보자.


.js file

g_app.controller('FirstFunc',

  [

    '$scope',

    function ($scope) {

      $scope.records = ['Thnx deal', 'TV Shopping', 'Shop plan', 'Department', 'ETC', 'ABC'];

      let list_width = 100 / $scope.records.length;

      $scope.list_width = {'width' : list_width.toString() + '%'};

  }

]);


.html file

    <ul class="list" ng-controller="FirstFunc">

      <li ng-style="list_width" ng-repeat="str in records">{{str}}</li>

    </ul>


이렇게 하면 리스트 갯수에 따라 자동으로 가로길이가 변경된다.

반응형

'Web > Angular1' 카테고리의 다른 글

[Angular1] module을 다른 module에 간단하게 inject해 보자  (0) 2016.12.17