컨트롤러에서 필터를 사용하는 방법은 무엇입니까?
전달하는 인수를 기반으로 데이터를 반환하는 필터 함수를 작성했습니다. 내 컨트롤러에서 동일한 기능을 원합니다. 컨트롤러에서 필터 기능을 재사용 할 수 있습니까?
이것이 내가 지금까지 시도한 것입니다.
function myCtrl($scope,filter1)
{
// i simply used the filter function name, it is not working.
}
컨트롤러에 $ filter 주입
function myCtrl($scope, $filter)
{
}
그런 다음 해당 필터를 사용하려는 경우 다음과 같이 사용하십시오.
$filter('filtername');
해당 필터에 인수를 전달하려면 별도의 괄호를 사용하여 수행하십시오.
function myCtrl($scope, $filter)
{
$filter('filtername')(arg1,arg2);
}
arg1
필터링 할 배열은 어디에 있으며 필터링에 arg2
사용되는 객체입니다.
@Prashanth가 제공 한 답변은 정확하지만 더 쉬운 방법이 있습니다. 기본적으로 $filter
의존성 을 주입하고 그것을 호출하는 어색한 구문을 사용 하는 대신 ( $filter('filtername')(arg1,arg2);
) 의존성을 주입 할 수 있습니다 : 필터 이름과 Filter
접미사.
질문에서 예를 들어 다음과 같이 작성할 수 있습니다.
function myCtrl($scope, filter1Filter) {
filter1Filter(input, arg1);
}
Filter
사용중인 명명 규칙에 관계없이 필터 이름에 추가해야한다는 점에 유의해야합니다 . foo는 다음을 호출하여 참조됩니다. foo는 다음을 호출 fooFilter
하여 참조됩니다.fooFilterFilter
다음 샘플 코드를 사용하여 각도 컨트롤러의 배열을 이름으로 필터링 할 수 있습니다. 이것은 다음 설명을 기반으로합니다. http://docs.angularjs.org/guide/filter
this.filteredArray = filterFilter (this.array, {name : 'Igor'});
JS :
angular.module('FilterInControllerModule', []).
controller('FilterController', ['filterFilter', function(filterFilter) {
this.array = [
{name: 'Tobias'},
{name: 'Jeff'},
{name: 'Brian'},
{name: 'Igor'},
{name: 'James'},
{name: 'Brad'}
];
this.filteredArray = filterFilter(this.array, {name:'Igor'});
}]);
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example96-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="FilterInControllerModule">
<div ng-controller="FilterController as ctrl">
<div>
All entries:
<span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
</div>
<div>
Filter By Name in angular controller
<span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>
</div>
</div>
</body>
</html>
Here's another example of using filter
in an Angular controller:
$scope.ListOfPeople = [
{ PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
{ PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
{ PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
{ PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
{ PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
{ PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];
$scope.ListOfWomen = $scope.ListOfPeople.filter(function (person) {
return (person.Sex == "Female");
});
// This will display "There are 2 women in our list."
prompt("", "There are " + $scope.ListOfWomen.length + " women in our list.");
Simple, hey ?
There are three possible ways to do this.
Let's assume you have the following simple filter, which converts a string to uppercase, with a parameter for the first character only.
app.filter('uppercase', function() {
return function(string, firstCharOnly) {
return (!firstCharOnly)
? string.toUpperCase()
: string.charAt(0).toUpperCase() + string.slice(1);
}
});
Directly through $filter
app.controller('MyController', function($filter) {
// HELLO
var text = $filter('uppercase')('hello');
// Hello
var text = $filter('uppercase')('hello', true);
});
Note: this gives you access to all your filters.
Assign $filter
to a variable
This option allows you to use the $filter
like a function
.
app.controller('MyController', function($filter) {
var uppercaseFilter = $filter('uppercase');
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Load only a specific Filter
You can load only a specific filter by appending the filter name with Filter
.
app.controller('MyController', function(uppercaseFilter) {
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Which one you use comes to personal preference, but I recommend using the third, because it's the most readable option.
function ngController($scope,$filter){
$scope.name = "aaaa";
$scope.age = "32";
$scope.result = function(){
return $filter('lowercase')($scope.name);
};
}
The controller method 2nd argument name should be "$filter" then only the filter functionality will work with this example. In this example i have used the "lowercase" Filter.
I have another example, that I made for my process:
I get an Array with value-Description like this
states = [{
status: '1',
desc: '\u2713'
}, {
status: '2',
desc: '\u271B'
}]
in my Filters.js:
.filter('getState', function () {
return function (input, states) {
//console.log(states);
for (var i = 0; i < states.length; i++) {
//console.log(states[i]);
if (states[i].status == input) {
return states[i].desc;
}
}
return '\u2718';
};
})
Then, a test var (controller):
function myCtrl($scope, $filter) {
// ....
var resp = $filter('getState')('1', states);
// ....
}
AngularJs lets you to use filters inside template or inside Controller, Directive etc..
in template you can use this syntax
{{ variable | MyFilter: ... : ... }}
and inside controller you can use injecting the $filter service
angular.module('MyModule').controller('MyCtrl',function($scope, $filter){
$filter('MyFilter')(arg1, arg2);
})
If you need more with Demo example here is a link
AngularJs filter examples and demo
There is another way to evaluate filters that mirrors the syntax from the views. The invocation is hairy but you could build a shortcut to it. I like that the syntax of the string is identical to what you'd have in a view. Looks like this:
function myCtrl($scope, $interpolate) {
$scope.$eval($interpolate( "{{ myvar * 10 | currency }} dollars." ))
}
It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);
For example:
$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});
Simple date example using $filter in a controller would be:
var myDate = new Date();
$scope.dateAsString = $filter('date')(myDate, "yyyy-MM-dd");
As explained here - https://stackoverflow.com/a/20131782/262140
Use below code if we want to add multiple conditions, instead of single value in javascript angular filter:
var modifiedArray = $filter('filter')(array,function(item){return (item.ColumnName == 'Value1' || item.ColumnName == 'Value2');},true)
First of all inject $filter to your controller, making sure ngSanitize is loaded within your app, later within the controller usage is as follows:
$filter('linky')(text, target, attributes)
Always check out the angularjs docs
if you want to filter object in controller try this
var rateSelected = $filter('filter')($scope.GradeList, function (obj) {
if(obj.GradeId == $scope.contractor_emp.save_modal_data.GradeId)
return obj;
});
This will return filtered object according to if condition
참고URL : https://stackoverflow.com/questions/14302267/how-to-use-a-filter-in-a-controller
'code' 카테고리의 다른 글
바이트 배열을 문자열로 변환하는 방법 (0) | 2020.10.02 |
---|---|
PuTTy 세션 목록을 내보내거나 가져 오는 방법은 무엇입니까? (0) | 2020.10.02 |
Eclipse, Subclipse 및 Subversive 용 SVN 플러그인의 장단점은 무엇입니까? (0) | 2020.10.02 |
위조, 조롱 및 스터 빙의 차이점은 무엇입니까? (0) | 2020.10.02 |
JSON을 간단한 사전으로 역 직렬화하는 방법 (0) | 2020.10.02 |