'2017/07/28'에 해당되는 글 2건

  1. 2017.07.28 [Angular] Service
  2. 2017.07.28 [angular] custom directive
2017. 7. 28. 12:05

controller에 늘어나는 변수와 함수들을 유사한 성격을 가진 것들을 묶어 service로 분리하여 코드를 관리


index.html

<!DOCTYPE html>

<html ng-app="web">

<head>

  <script data-require="angular.js@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>

  <link rel="stylesheet" href="style.css" />


  <script src="app.js"></script>

  <script src="controller.js"></script>

  <script src="service.js"></script>  

</head>


<body ng-controller="ctrl">

  <h1>{{Data}}</h1>

</body>

</html>


app.js

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


controller.js

// myService의 명시적으로 선언하여 사용

app.controller("ctrl", ["$scope", "myService", function($scope, myService) {

  $scope.Data = myService.get();

}]);

// 또는

app.controller("ctrl", function($scope, myService) {

  $scope.Data = myService.get();

});


service.js

app.factory("myService", function() {

  var service = {

    Data:  "Datasafasfsad",

    

    get: function() {

      return service.Data;

    }

  }

  // controller에서 사용할 object를 리턴

  return service;

});


샘플

Posted by CoolDragon
2017. 7. 28. 10:29

간단 사용자 지시자(custom directive) 만들기


<!DOCTYPE html>

<html ng-app="web">

<head>

  <script data-require="angular.js@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>

  <link rel="stylesheet" href="style.css" />

  <script src="script.js"></script>

  <script src="directives.js"></script>

</head>


<body ng-controller="WebController">

   <!--angular에서 카멜케이스로 지정하지만 여기서는 '-'으로 구분 -->

  <div>

    <my-title />

  </div>


  <ul ng-repeat="Fruit in Fruits">

    <my-item />

  </ul>

</body>

</html>


script.js

(function() {

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


  app.controller("WebController", ["$scope", function($scope) {

    $scope.Fruits = ['Apple', 'Orange', 'Cherry'];

    $scope.Title = "TEST";

  }])

})();


directives.js

// 지시자 이름을 카멜케이스로 한다.

angular.module('web').directive('myTitle', function() {

  return {

    template: '<h1>테스트</h1>'

  }

});


angular.module('web').directive('myItem', function() {

  return {

    templateUrl: 'item.tmpl.html'

  }

});


item.template.html

<li>{{Fruit}}</li>



샘플

Posted by CoolDragon