I am passing date
value to my custom filter this way:
angular.module('myapp'). filter('filterReceiptsForDate', function () { return function (input, date) { var out = _.filter(input, function (item) { return moment(item.value.created).format('YYYY-MM-DD') == date; }); return out; } });
I would like to inject a couple of scope variables there too, like what I can do in directives. Is that possible to do this without having to passing these vars explicitly as function arguments?
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .
Apparently you can.
Usually you would pass scope variables to the filter as function parameter:
function MyCtrl($scope){ $scope.currentDate = new Date(); $scope.dateFormat = 'short'; }
<span ng-controller="MyCtrl">{{currentDate | date:dateFormat}}</span> // --> 7/11/13 4:57 PM
But, to pass the current scope in, you'd have to pass this
:
<span ng-controller="MyCtrl">{{currentDate | date:this}}</span>
and this
will be a reference to current scope:
Simplified:
app.controller('AppController', function($scope) { $scope.var1 = 'This is some text.'; $scope.var2 = 'And this is appended with custom filter.'; } ); app.filter('filterReceiptsForDate', function () { return function (input, scope) { return input + ' <strong>' + scope.var2 + '</strong>'; }; });
<div ng-bind-html-unsafe="var1 | filterReceiptsForDate:this"></div> <!-- Results in: "This is some text. <strong>And this is appended with custom filter.</strong>" -->
PLUNKER
I found that this
references local $scope
. Not sure if this is safe way of accessing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With