Phate
Phate

Reputation: 6622

How to call a function defined in the controller inside of the view?

I know I can display a scope variable value by doing:

<div> This is my var value: {{myVar}} </div>

Suppose I have this function

$scope.displayVal = function(){
         return myVar+5;
};

Is there a way to call it in a similar way?

Upvotes: 4

Views: 16112

Answers (4)

On a side note this is how you would create the function:

$scope.displayVal = function displayVal(){
         return myVar+5;
};

After the key word function you would need to enter the name of the function.

Upvotes: 0

Ernani
Ernani

Reputation: 339

Since your function is declared in the scope, you can call it normally in (what I assume is) your view; for example:

// code in the controller
$scope.myVar = 10;

$scope.displayVal = function(){
  return myVar + 5;
};

// code in the view
<input type="text" ng-model="displayVal()" /> // 15 will appear in the box

You can also call the function within a button; as to where the value will appear, I'll leave it to you:

<input type="button" value="Display Value" ng-click="displayVal()" />

Upvotes: 0

Shyju
Shyju

Reputation: 218892

<div>{{displayVal()}}</div>

or

<div ng-bind="displayVal()"></div>

If you use Controller as syntax

<div ng-controller="YourController as vm">
    <div>{{vm.displayVal()}}</div>
</div>

Upvotes: 10

Ali Adravi
Ali Adravi

Reputation: 22833

It can be used directly like a function:

<div>{{displayVal()}}</div>

If you are initializing some values and want to call on page load then

<div ng-init="displayVal()"></div>

Upvotes: 1

Related Questions