[英]Filter for search result with AngularJS
A quick question: 一个简单的问题:
I'm creating a filter in angularjs to get dynamically a variable and to be used like this from frontend. 我在angularjs中创建了一个过滤器,以动态获取变量并从前端像这样使用。
<div ng-if="(services | searchValue : 'type' : 'facebook').active == true">
...
</div>
This is the javascript. 这是javascript。
.filter('searchValue', function () {
return function (array, name_var, value) {
angular.forEach(array, function(v, k) {
if (v[name_var] == value) {
return v;
}
});
return [];
};
})
Unfortunately even if the result was found it wasn't passed to the template. 不幸的是,即使找到结果,也没有将其传递给模板。
If I'll use it like this: 如果我这样使用它:
{{(services | searchValue : 'type' : 'facebook')}}
This will get no value. 这将毫无价值。 Any suggestion? 有什么建议吗?
I've created a sample example for the info you've provided. 我已经为您提供的信息创建了一个示例示例。 Run the below example check. 运行以下示例检查。 Hope this helps you. 希望这对您有所帮助。
I guess ng-if
itself expects only the variable and not the expression. 我想ng-if
本身只希望变量而不是表达式。 only provide the variable with value ie (services | searchValue : 'type' : 'facebook').active
not the expression . 只为变量提供值,即(services | searchValue : 'type' : 'facebook').active
而不是expression 。
var app = angular.module('application', []); app.filter('customfilter', function() { return function(array, name_var, value) { var filteredArray = {}; angular.forEach(array, function(v, k) { if (v[name_var] == value) { filteredArray = v; return false; } }); return filteredArray; } }); app.controller('sampleController', function($scope, $filter) { $scope.data = [{ "type": "facebook", "active": false }, { "type": "linkedin", "active": false }, { "type": "twitter", "active": false }, { "type": "google", "active": false }]; $scope.anotherdata = [{ "type": "facebook", "active": true }, { "type": "linkedin", "active": false }]; });
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17"></script> <body ng-app="application"> <div ng-controller="sampleController"> First div - Active : false <div ng-if="(data | customfilter:'type':'facebook').active"> Your div content goes over here </div> <br> <br>Second div - Active : true <div ng-if="(anotherdata | customfilter:'type':'facebook').active"> Second div rendered </div> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.