简体   繁体   English

如何在angularJS中访问Java脚本中的HTML变量

[英]How to access HTML variable in Java-script in angularJS

I am filling a select list in angularJS. 我在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. 哪个打印categoryID。

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

But i want to access both categoryID nad categoryName in this update function. 但我想在此更新功能中同时访问categoryID和categoryName。 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. 如何在此更新函数中同时获取categoryID和categoryName。

Change your html to this: 将您的html更改为此:

<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 这会将整个类别存储在NewProduct.category中,而不仅仅是ID

Try to change to: 尝试更改为:

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

You are passing in to the update function the current category. 您正在将当前类别传递给更新功能。 Access it by the value parameter. 通过value参数访问它。

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

You should pass a object in ng-options like 您应该在ng-options传递一个对象,例如

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

And you will get complete object in update function. 并且您将在更新功能中获得完整的对象。

Maybe you should add toString() at the end of each value: 也许您应该在每个值的末尾添加toString()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM