테스트 사이트 - 개발 중인 베타 버전입니다

AngularJS Services 필터 내부에서 사용자 지정 서비스 사용

· 8년 전 · 1481
AngularJS Services 필터 내부에서 사용자 지정 서비스 사용


일단 서비스를 생성하고 애플리케이션에 연결하면 컨트롤러, 지시문, 필터 또는 다른 서비스 내부에서 서비스를 사용할 수 있습니다.

필터에서 서비스를 사용하려면 필터를 정의 할 때 서비스를 종속으로 추가하십시오.

hexafy필터에 사용 된 서비스 myFormat:

app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp">
Convert the number 255, using a custom made service inside a custom made filter:

<h1>{{255 | myFormat}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);

</script>

</body>
</html>


객체 또는 배열의 값을 표시 할 때 필터를 사용할 수 있습니다.

다음과 같은 서비스를 만듭니다 hexafy.

<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

[전체소스]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<p>Use a filter when displaying the array [255, 251, 200]:</p>

<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

<p>This filter uses a service that converts numbers into hexadecimal values.</p>
</div>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);
app.controller('myCtrl', function($scope) {
$scope.counts = [255, 251, 200];
});
</script>

</body>
</html>

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
1386
1385
AngularJS 주형
1384
AngularJS 컨트롤러
1383
1382
1381
1380
1379
1378
1377
1376
1375
1374
1373
1372
1371
1370
AngularJS AngularJS API
1369
AngularJS 검증 예제
1368
1367
AngularJS CSS 클래스
1366
1365
AngularJS 이메일
1364
1363
AngularJS 선택 상자
1362
1361
AngularJS 체크 박스
1360
1359
AngularJS $event 객체
1358
1357