如何使$变量范围内的过滤器指令的控制器 [英] how to make filters with $scope variables inside controllers of directives
问题描述
我发现很多约定写code角中的JS。我使用以下约定。
I have found lot of conventions to write code in angular JS. I am using the following convention.
app.directive("employeeList" , function(){
return {
restrict : 'E' ,
templateUrl: 'employee-list.html',
controller:function($scope , $filter)
{
$scope.emp_positions = positions_json; // my FIREST array
$scope.emp_users_json = users_json; // My SECOND Array
//My Code Logic //
// I WANT TO MAKE FILTER HERE WHICH CAN USE $SCOPE VARIABLE.
IS THERE ANY WAY TO MAKE FILTER HERE LIKE
$SCOPE.FILTER('FLITER_NAME' , FUNCTION($SCOPE)){....} ???
IS IT POSSIBLE? IF NOT WHAT COULD BE OTHER POSSIBLE WAY.
//
},
controllerAs: 'emp'
};
});
现在我要编写定制过滤器来过滤我的数据现在是在$范围变量。
1)我可以写控制器内的自定义过滤器,它使用$范围的变量。如果是的话,那怎么请给我的例子。
如果没有的话,我可以尽到$范围变量传递给自定义变量是指令之外还有什么?
Now I want to write the custom filter for filtering my data which is now in "$scope" variable. 1)Can I write the custom filter inside controller which uses $scope variable. If yes, Then how Please give me example. if not then what else I can do to pass the $scope variable to the custom variable which is outside the Directive.?
http://plnkr.co/edit/J0xCIP9d5boJzostGEv8?p=$p$ PVIEW
我已经加入我的plunker请阅读表POSITION HERENAD也看过我的script.js文件。并为数据我已经添加data.js文件
I have added my plunker please read in table "POSITION HERE" nad also read my script.js file. and for the data i have added data.js file
推荐答案
更新:
关于使用$范围进入过滤器。
About using of $scope into the filter.
1),你会从指令传递范围变量过滤器的功能参数,并从 ARGS
对象访问它们:
1) You would pass scope variables from directive to the filter as function parameter and get access to them from args
object:
app.directive("employeeList" , function(){
return {
restrict : 'E' ,
templateUrl: 'employee-list.html',
controller:function($scope)
{
$scope.emp_positions = positions_json;
$scope.emp_users_json = users_json;
//your another code here
},
controllerAs: 'emp'
};
});
您员工list.html
<div ng-repeat="employee in employees | employeeFilter: [emp_positions, emp_users_json]">
.....
</div>
您过滤器:
app.filter('employeeFilter', function () {
return function (input, args) {
console.log(args[0]); //$scope.emp_positions here
console.log(args[1]); //$scope.emp_users_json here
var inputArray = input;
return inputArray;
}
});
2)你会通过传递经过整个$范围过滤器这个
。
这个
将是目前规模的参考。
this
will be a reference to current scope.
<div ng-repeat="employee in employees | employeeFilter: this">
.....
</div>
您过滤器:
app.filter('employeeFilter', function () {
return function (input, args) {
console.log(args[0]); //whole $scope from directive here
var inputArray = input;
return inputArray; //returned value from filter
// in this case returned array equals to the initial input
}
});
P.S。但是,我建议选择第一个选项,只传递范围的变量,而不是整个$范围。
P.S. But I suggest to choose the first option and pass only scope variables, not whole $scope.
我已经更新您的plunker。
I've updated your plunker.
请参阅: plunker
这篇关于如何使$变量范围内的过滤器指令的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!