웹개발 및 최신 테크 소식을 전하는 블로그, 웹이즈프리

HOME > angularjs

Angular factory() 메소드로 서비스 모듈 만들기

Last Modified : 2017-08-11 / Created : 2017-06-20
4,171
View Count
AngularJS에서 모듈을 생성하고 사용하는것은 매우 중요한 부분입니다. 아래는 .factory()를 사용하여 커스텀 서비스를 만들고 이를 디렉티브에 적용하여 사용하는 간단한 예제입니다.

먼저 myApp에 커스텀서비스인 customServices를 생성하고 서비스명 testService에 메세지를 보여줄 showmsg() 메소드를 만들어봅니다.

angular.module('customServices', [])
.factory('testService', function() {
  return {
    showmsg: function(name) {
      return name;
    }
  }
});

이제 testService를 적용한 후 showmsg()를 사용하여 출력해보겠습니다. 아래는 전체 마크업된 코드입니다.

<html ng-app="myApp" ng-controller="testController"> 
  <body>
    <div>
      Test - service injection <br />

      {{ testStr }}
    </div>
    
    <script>
      angular.module('myApp', ['customServices'])
      .controller('testController', function($scope, testService) {
        $scope.testStr = testService.showmsg('123456');
        
      });
      angular.module('customServices', [])
      .factory('testService', function() {
        return {
          showmsg: function(name) {
            return name;
          }
        }
      });
   
</script>
  </body>
</html>

이처럼 서비스를 직접 만들어 사용하는 것이 가능합니다.


code snippet widget

Previous

angularjs에서 ngNonBindable 디렉티브를 사용한 컴파일 피하기

Previous

AngularJS에서 ngChecked 사용하여 체크박스, 라디오 체크 변경하기