使用 ng-change 选择 ng-object [英] getting the ng-object selected with ng-change

查看:28
本文介绍了使用 ng-change 选择 ng-object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下选择元素

<select ng-options="size.code as size.name for size in sizes " 
        ng-model="item.size.code" 
        ng-change="update(MAGIC_THING)">
</select>

有没有办法让 MAGIC_THING 等于当前选择的大小,这样我就可以在我的控制器中访问 size.namesize.code?

Is there a way to get MAGIC_THING to be equal to the currently selected size, so I have access to size.name and size.code in my controller?

size.code 会影响应用程序的许多其他部分(图片网址等),但是当 item.size.code 的 ng-model 更新后,item.size.name 也需要针对面向用户的内容进行更新.我认为正确的方法是捕获更改事件并在我的控制器内设置值,但我不确定我可以将什么传递给 update 以获得正确的值.

size.code affects a lot of the other parts of the app (image urls, etc), but when the ng-model of item.size.code is updated, item.size.name needs to be updated as well for the user facing stuff. I assume that the correct way to do this is capturing the change event and setting the values inside of my controller, but I'm not sure what I can pass into update to get the proper values.

如果这是完全错误的方法,我很想知道正确的方法.

If this is completely the wrong way to go about it, I'd love to know the right way.

推荐答案

不是将 ng-model 设置为 item.size.code,而是将其设置为 size :

Instead of setting the ng-model to item.size.code, how about setting it to size:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

然后在您的 update() 方法中,$scope.item 将设置为当前选定的项目.

Then in your update() method, $scope.item will be set to the currently selected item.

以及任何需要的代码 item.size.code,都可以通过 $scope.item.code 获取该属性.

And whatever code needed item.size.code, can get that property via $scope.item.code.

小提琴.

更新基于评论中的更多信息:

Update based on more info in comments:

为您选择的 ng-model 使用其他一些 $scope 属性,然后:

Use some other $scope property for your select ng-model then:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

控制器:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

这篇关于使用 ng-change 选择 ng-object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆