0

In Angular JS application I need to show user the result of the javascript function (heavyFunction in my example), which depends on user input, so I am using {{}} to show the result.

I need to show it only in certain conditions, so I am also invoking this function in ng-show and ng-class directives.

<span ng-show="heavyFunction() > 0" ng:class="{true:'red', false:'blue'}[heavyFunction() > 5]"> {{heavyFunction()}} </span>

The problem is that I am invoking function three time, instead of one time. What is the best practice in Angular JS to invoke this function only once?

Plunker: https://plnkr.co/edit/9r5AlA3RbtZLseOCOzPX?p=preview

0

2 Answers 2

1

You can use ngBind

Like this

ng-bind="total=heavyFunction()"

HTML

<p>a + b:</p> <span ng-bind="total=heavyFunction()" ng-show="total > 0" ng-class="{true:'red', false:'blue'}[total > 5]"> {{total}} </span>

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing Anik! This works, just for some reason heavy still invokes two time, but at least not 6 times as it was before!
0

One way to achieve this in your example is to use ngChange. On input value change, bind a function that gets triggered, which call the heavy function.

$scope.numberChanged = function() {
    $scope.heavyFunction();
};

Then in html, bind the ng change:

<input type="number" ng-model="a" ng-change="numberChanged()"></input>
<input type="number" ng-model="b" ng-change="numberChanged()"></input>

Then make sure that the heavy function is caching the result:

$scope.heavyFunction = function() {
    $scope.result = $scope.a + $scope.b;
};

And in the ui, changes classes and display output by binding the the cached result:

<p>a + b:</p> <span ng-show="result > 0" ng:class="{true:'red', false:'blue'}[result > 5]"> {{result}} </span>

On a side not, if you have a function that has to be executed by html by only once, you can make use of one time binding built into angularJs. https://docs.angularjs.org/guide/expression#one-time-binding

1 Comment

Chanthu, thanks, but this solution will require to have ng-change on every element, which I would like to avoid.

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.