Exitos
Exitos

Reputation: 29720

How do I pass a html value into an AngularJS method?

I am trying to pass a value from a html element angularJS method bound to the $scope.

The code is...

<div ng-app ng-controller="miniC">

      <input name="someitem" ng-blur="CalculateTotals(this)"/>

</div>

function miniC($scope){


    $scope.myAccounts =  new Array();

    $scope.CalculateTotals = function(amt){

        console.log(amt);

    }


}

codepane link

But I cannot seem to extract the value from the element. I do not want to bind in this case as I am trying some things out and this was one of the approaches I had....

Upvotes: 1

Views: 3068

Answers (3)

raina77ow
raina77ow

Reputation: 106395

The easiest way is to turn an input into a model's representation with ng-model directive, allowing to access its value directly. But if, for some reasons, you don't want to do this, you still can access this element - via target property of $event variable exposed by ngBlur directive. For example:

HTML:

<div ng-app ng-controller="miniC">
    <input name="someitem" ng-blur="AddToTotal($event.target)" />
    <button type="button" ng-click="Reset()">Reset</button>
    <br />
    <span>Totals: {{ CalculateTotals() }}</span>
</div>

JS:

function miniC($scope) {
    $scope.myAccounts = [];

    $scope.Reset = function() {
        this.myAccounts.length = 0;
    }

    $scope.CalculateTotals = function() {
        return this.myAccounts.reduce(function(sum, el) {
            return sum + el;
        }, 0);
    };

    $scope.AddToTotal = function(inp) {
        var value = inp.value;
        this.myAccounts.push(+value);
    };
}

Demo. It works somewhat funny, as a new value is added each time focus is moved out of that input.

Upvotes: 0

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1349

Append ng-model="testVal" to your input field and console.log($scope.testVal); to log your value.

Upvotes: 0

Ed_
Ed_

Reputation: 19098

Angular expressions are all properties of the scope they are evaluated on, so this will just be the current scope.

With this in mind, you have to make this available on the scope. The simplest way is to use ng-model="someValue", then use ng-blur="CalculateTotals(someValue)".

However I also note in your question you explicitly don't want to bind, and this does add some overheads if you don't use anything else, so you would have to create a custom directive instead.

Upvotes: 1

Related Questions