Home  >  Article  >  Web Front-end  >  Mixed use of AngularJS custom services and filter

Mixed use of AngularJS custom services and filter

高洛峰
高洛峰Original
2016-12-05 14:09:211060browse

In angular, Filter is used to format data. For example, in projects, there are many times when the data taken from the background is displayed directly and the user does not understand its meaning. At this time, we need to format it ourselves before displaying it on the interface. In traditional J, we need a long list of codes and various innuendoes, but the filter provided by angular does require a lot of introduction.

The following will introduce to you the mixed use of angularJS custom services and filter, let’s take a look.

1. Create a custom service "$swl"

var app = angular.module('myApp', []);
app.service("$swl", function() {
this.after = function(data) {
return "("+data + " after,$swl";
};
this.before = function(data) {
return "($swl,before " + data+")";
}
})

2. Call the custom service through the controller

html code

<div ng-app="myApp" ng-controller="myCtrl">
{{name }}
</div>

controller code

app.controller("myCtrl", function($scope, $swl,$timeout) {
$scope.name = $swl.before("swl");
$timeout(function(){
$scope.name = $swl.after("swl");
},2000)
})

3. with Mixed use of fliter

html code

<div ng-app="myApp" ng-controller="myCtrl">
{{name | before}}
</div>

fliter code

app.filter("before",["$swl",function($swl){
return function(data){
return $swl.before("(filter,"+data+")");
}
}])


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn