AngularJS - Can't use filter to set variable in view

时间:2015-06-15 14:29:50

标签: angularjs

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 个答案:

答案 0 :(得分: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;
};