0

I'm using a filter to calculate values, but then I want to access them later on.

Here's a snippet of my code:

app.controller('CreateProposalCtrl', function() {
     $scope.EstimatedCostItem = [];
});

-

app.filter('EstimatedValue', function() {
        return function(input, arguments) {
             ...blah blah calculations
             return calculations;
        };
    });

I'm not sure how the HTML should be presented.

This displays exactly what I want..BUT I need it to set a variable so I can access it somewhere else..

<span ng-repeat="foo in bar">
    {{ Type.JobTypeID | EstimatedValue: form }}
</span>

I've tried:

<span ng-model="EstimatedCostItem[Type.JobTypeID]" ng-bind="Type.JobTypeID | EstimatedValue: form"></span>

And:

<span ng-bind="EstimatedCostItem[Type.JobTypeID]">{{ Type.JobTypeID | EstimatedValue: form }}</span>

And:

<span ng-init="EstimatedCostItem[Type.JobTypeID] = (Type.JobTypeID | EstimatedValue: form)"></span>

Nothing seems to set a variable. I'm stumped :(

1
  • When do you need to set a variable ? Commented Jun 15, 2015 at 14:32

1 Answer 1

1

The filter syntax only works within specific Angular expressions. Expressions that use plain JavaScript cannot use the foo | bar filter syntax, as it's not valid JavaScript.

What you could do is use $filter:

var value = $filter('EstimatedValue')(foo);

Remember to inject $filter into your controller.

With that said, this probably isn't the best use of a filter. Why not create a scope function that calculates and stores the value? Something like:

$scope.EstimatedValue = function(foo) {
    var value = doSomeCalculations();

    // store for usage elsewhere
    this.estimatedValuesCache[foo] = val;

    return val;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Great. Thanks for this. To answer your question, I want to reuse my filter in other controllers so don't want to copy over a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.