Devesh Agrawal
Devesh Agrawal

Reputation: 9212

How to access HTML variable in Java-script in angularJS

I am filling a select list in angularJS. This is the code.

<select class="form-control" ng-model="NewProduct.category" ng-options="category.id as category.name for category in Categories | orderBy:['name']" ng-change="update(NewProduct.category)" required></select>

On change it calls update function; which print categoryID.

$scope.update = function (value) {
    alert ($scope.NewProduct.category);
};

But i want to access both categoryID nad categoryName in this update function. I tried:

$scope.update = function (value) {
    alert ($scope.NewProduct.category.id);
    alert ($scope.NewProduct.category.name);

};

But it alerts undefined, undefined.

How to get both categoryID nad categoryName in this update function.

Upvotes: 0

Views: 140

Answers (5)

Mathew Berg
Mathew Berg

Reputation: 28750

Change your html to this:

<select class="form-control" ng-model="NewProduct.category" ng-options="category as category.name for category in Categories | orderBy:['name']" ng-change="update(NewProduct.category)" required></select>

This will store the entire category in NewProduct.category instead of just the id

Upvotes: 1

Vineet
Vineet

Reputation: 4655

You should pass a object in ng-options like

ng-options="category as category.name for category in Categories | orderBy:['name']"

And you will get complete object in update function.

Upvotes: 0

Fran Martinez
Fran Martinez

Reputation: 3052

Maybe you should add toString() at the end of each value:

alert (value.id.toString());
alert (value.name.toString());

Upvotes: 0

area28
area28

Reputation: 1425

You are passing in to the update function the current category. Access it by the value parameter.

$scope.update = function (value) {
    alert (value.id);
    alert (value.name);
};

Upvotes: 0

Johnny Ha
Johnny Ha

Reputation: 633

Try to change to:

$scope.update = function(value) {
   alert(value.id);
   alert(value.name);
};

Upvotes: 0

Related Questions