I want to use multiple filters in controller
Currently using
$filter('limitTo')($filter('lowercase')($filter('translate')('ACTIVE')), 5)
If we have more filters like this. How can I use multiple filters in controller rather conventional format like this?
You can simply introduce variables:
var limitTo = $filter('limitTo');
var lowercase = $filter('lowercase');
var translate = $filter('translate');
var filteredValue = limitTo(lowercase(translate('ACTIVE')), 5);
Or even
var lowercaseStatus = lowercase(translate('ACTIVE'));
var filteredValue = limitTo(lowercaseStatus, 5);
Another strategy would be to use the same syntax as in the view:
var filteredValue = $scope.$eval('"ACTIVE" | translate | lowercase | limitTo:5');
This is an interesting question. Usually you would do something like that or something like this:
var translatedValue = $filter('translate')('ACTIVE');
var lowercaseValue = $filter('lowercase')(translatedValue);
$scope.finalValue = $filter('limitTo')(lowercaseValue, 5)
I created a service inspired by this answer.
app.service('FilterChain',
['$filter', function($filter) {
var chain = {
value : '',
start : function(value) {
this.value = value;
return this;
},
applyFilter : function(filterName, args) {
args = args || [];
args.unshift(this.value);
this.value = $filter(filterName).apply(undefined, args)
return this;
}
};
return chain;
}]);
Usage is like this
$scope.value = FilterChain.start('Active')
.applyFilter('translate')
.applyFilter('limitTo', [5])
.applyFilter('uppercase')
.value;
You can use the service with other filters and objects such as arrays. See a working example here: JSFiddle
Related
I'm using angularjs 1.5.8 to basically mimic an excel table with equations. THere are three rows requiring two inputs that affect two outputs. I'm struggling on how to write my script to include multiple controllers as I'm building a controller for each row. If I comment out the second and third controller in my script, the first row works just fine. When no lines are commented, nothing works. I feel like I'm very close but not sure where I'm going wrong. Any help would be appreciated.
Here is the working controller:
angular.module('ADMApp', [])
.controller('ADMFarViewController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADMFarViewImgHeightvar = Number(ctrl.ADMFarViewImgHeightvar || 0);
var ADMFarViewVertPixvar = Number(ctrl.ADMFarViewVertPixvar || 0);
ctrl.ADM_FarViewFarthestViewer_ans = (ADMFarViewImgHeightvar * 3438) / ADMFarViewVertPixvar;
ctrl.ADM_FarViewViewRat_ans = ctrl.ADM_FarViewFarthestViewer_ans / ADMFarViewImgHeightvar;
}
}]);
Here is my plunker: https://plnkr.co/edit/6nKEPCeOqx7zEFx5M5WZ
Don't redefine your module every time.
// Code goes here
var ADMApp = angular.module('ADMApp', []);
ADMApp.controller('ADMFarViewController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADMFarViewImgHeightvar = Number(ctrl.ADMFarViewImgHeightvar || 0);
var ADMFarViewVertPixvar = Number(ctrl.ADMFarViewVertPixvar || 0);
ctrl.ADM_FarViewFarthestViewer_ans = (ADMFarViewImgHeightvar * 3438) / ADMFarViewVertPixvar;
ctrl.ADM_FarViewViewRat_ans = ctrl.ADM_FarViewFarthestViewer_ans / ADMFarViewImgHeightvar;
}
}]);
ADMApp.controller('ADMMinImgController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADM_MinImgHeightVertPix_var = Number(ctrl.ADM_MinImgHeightVertPix_var || 0);
var ADM_MinImgHeightFarthestViewer_var = Number(ctrl.ADM_MinImgHeightFarthestViewer_var || 0);
ctrl.ADM_MinImgHeightImageHeight_ans = (ADM_MinImgHeightVertPix_var * ADM_MinImgHeightFarthestViewer_var) / 3438;
ctrl.ADM_MinImgHeightViewRat_ans = ADM_MinImgHeightFarthestViewer_var / ctrl.ADM_MinImgHeightImageHeight_ans;
}
}]);
ADMApp.controller('ADMMaxImgController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADM_MaxImgImageHeight_var = Number(ctrl.ADM_MaxImgImageHeight_var || 0);
var ADM_MaxImgFarthestViewer_var = Number(ctrl.ADM_MaxImgFarthestViewer_var || 0);
ctrl.ADM_MaxImgVertPix_ans = (ADM_MaxImgImageHeight_var * 3438) / ADM_MaxImgFarthestViewer_var;
ctrl.ADM_MaxImgViewRat_ans = ADM_MaxImgFarthestViewer_var / ADM_MaxImgImageHeight_var;
}
}]);
angular.module('ADMApp', [])
That line of code defines the module 'ADMApp'. Since you hve this line three times in your code, you define the same module thrice, effectively overwriting its previous definition, containing the previously added controller.
Save it in a variable, or use angular.module('ADMApp')to get a reference to the previously defined module.
I have sample Json. I am fiter based on key value.
The fiter didn't sort exact value
Example:
angular.module('myApp').controller('testController', ['$filter', '$scope',
function($filter, $scope) {
var obj = '[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"},
{"id":"45","m_id":9,"value":"Single"},
{"id":"46","m_id":9,"value":"Married"},
{"id":"47","m_id":10,"value":"Father"},
{"id":"48","m_id":10,"value":"Mother"},
{"id":"61","m_id":10,"value":"Cousin"},
{"id":"62","m_id":10,"value":"Other"}]';
var obj1 = JSON.parse(obj);
var result = $filter('filter')(obj1, {
m_id : "1"
});
}]);
Output:
[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"},
{"id":"47","m_id":10,"value":"Father"},
{"id":"48","m_id":10,"value":"Mother"},
{"id":"61","m_id":10,"value":"Cousin"},
{"id":"62","m_id":10,"value":"Other"}]
Expected Output:
[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"}]
Click here
You can do this way also, by using Javascript Filter():
var result = obj1.filter(function(v){
return v.m_id == 1;
});
DEMO
In AngularJS v.1.1.3 exact filter is provided natively
var result = $filter('filter')(obj1,
{m_id : 1},
true // ==========> this is for exact match
);
Working DEMO
Change
var result = $filter('filter')(obj1, {
m_id : "1"
});
to
var result = $filter('filter')(obj1, function(item) { return item && item.m_id == 1; });
Demo here
I have 3 switches (checkboxes, they return true or false) to filter in a list.
The list:
vm.products = Product.query();
In my controller, i want to filter vm.products, everytime one of the switchboxes/checkboxes get changed.
All i got so far, is a none working, filter argument:
vm.products = $filter('filter')('id', 1);
The parameter 'filter' - sems like its pointing at a directive? Do i have to do that? And what would be the best way of making a dynamic filter function/builder, when there is multiple values to check on?
I found a way using a custom filter;
.filter("myFilter", function(){
return function(products, productTypes){
var selectedProducts = [];
for (i = 0; i < products.length; i++) {
if (productTypes.indexOf(products[i].productTypeId.toString()) > -1) {
selectedProducts.push(incidents[i]);
}
}
return selectedProducts;
};
})
I then use this in my controller to call the filter function;
vm.filterTypeUpdated = function ($event, typeId) {
var productTypesId = "";
if (vm.filterType1)
productTypesId += "1,";
if (vm.filterType2)
productTypesId += "2,";
if (vm.filterType3)
productTypesId += "3,";
vm.productsRoot = $filter('myFilter')(vm.products, productTypesId);
}
I don't feel like this is the cleanest way of doing it, but it works. If there are any inputs on optimizing this, i am all ears :-)
I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:
buildMyArray: function() {
var self = this;
var myArray = {};
window.myLibrary.getStuff('myParameter', function(myStuff) {
for (var myKey in myStuff) {
if (myStuff.hasOwnProperty(myKey)) {
var myValue = myStuff[myKey];
myArray[myKey] = myValue;
}
}
self.set({ myArray: myArray });
});
}
However, how can I access that array from other properties? In other words, I want to do something like this:
checkArrayStuff: function(arrayKey) {
//loop through myArray and check value for arrayKey.
//var myArray1 = self.get(myArray);
//var myArray2 = this.get(myArray);
//var myArray3 = myArray;
//var myArray4 = this.myArray;
//var myArray5 = self.get('myArray');
//var myArray6 = this.get('myArray');
var myArray7 = self.myArray;
var can = myArray7[arrayKey];
return can;
}
I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.
I guess you would have to do this
checkArrayStuff: function(arrayKey) {
return this.get('myArray')[arrayKey];
}
this.get('myArray') should work but it looks like your window.myLibrary.getStuff function is asynchronous. That means myArray won't be set until some time after buildMyArray returns. If you give us more context we can make a better recommendation of how to address this such as having buildMyArray call checkArrayStuff after it's done the .set(..) or having buildMyArray return a promise
I have a Backbone Model in which there are certain properties like
test_id
test_name
test_desc
test_score
Now I want to retrieve properties which are starting with "test_".
I tried with code below and its working fine.
var MyModel = Backbone.Model.extend({
getTestProperties: function(str){
// get clone of attributes to iterate over
var testProperties = {};
var attrs = _.clone(this.attributes);
_.each(attrs, function(val, key){
if(key.indexOf(str) == 0){
testProperties[key]= val;
}
}, this);
}
});
But
Is there any other way I can get these properties using underscore methods ?
Thanks
Backbone proxies some methods from Underscore on models that can help you create a more readable _.filter: _.keys and _.pick
You can then simplify your function like this :
var MyModel = Backbone.Model.extend({
getTestProperties: function (str) {
// get the keys you want
var keys = _.filter(this.keys(), function (key) {
return key.indexOf(str) === 0;
});
// and build an object
return this.pick(keys);
}
});
And a demo http://jsfiddle.net/nikoshr/5a63c/
Try something like
var attrs = _.filter(_.keys(_.clone(this.attributes)), function(attr){
return attr.indexOf("text_") === 0;
});