javascript - 如何在AngularJS中onchange后获取选项文本值
问题描述
我有一个选择下拉菜单,在更改“城市”时,我得到的是先前选择的值,而不是当前选择的值。例如:如果我选择状态,然后再次选择城市,则 div 文本处于状态显示警报,但我想显示 div 文本来自城市。再次,我想将所有值显示为一条消息,在这里我只能显示最后一个值。任何人都可以在这两个问题上帮助我。这是下面的代码。
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" class="test" ng-attr-id="{{emp[attr]}}"><p>{{emp[attr]}}</p></div>
<div class="error">{{col}}</div>
</div>
</div>
脚本
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'one'
},
{
title: 'title2',
name: 'name2',
details: 'two'
},
{
title: 'title3',
name: 'name2',
details: 'three'
}
]
$scope.update = function() {
if ($scope.x == 'city') {
$scope.id = 'city';
$scope.attr = 'details';
$('div.test').each(function(i,div){
var listitem = div;
$scope.col = $(div).find("p").text();
alert($scope.col);
});
}
if ($scope.x == 'state') {
$scope.id = 'state';
$scope.attr = 'title';
}
if ($scope.x == 'country') {
$scope.id = 'country';
$scope.attr = 'name';
}
}
});
解决方案
我测试了您的代码,基本的 angularjs 语法看起来是正确的,并且可以正常工作。
您应该考虑的是避免混合使用 jQuery 和 angularjs。jQuery 能做什么——你可以用 angularjs 做,angularjs 的方式,你只需要学习它。
这是一个工作示例,我在其中删除了您的 jQuery 内容。
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'details1'
},
{
title: 'title2',
name: 'name2',
details: 'details2'
},
{
title: 'title3',
name: 'name3',
details: 'details3'
}
]
$scope.update = function() {
if ($scope.id == 'city') {
$scope.attr = 'details';
}else if ($scope.id == 'state') {
$scope.attr = 'title';
}else if ($scope.id == 'country') {
$scope.attr = 'name';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="id" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" class="test" ng-attr-id="{{emp[attr]}}"><p>{{emp[attr]}}</p></div>
<div class="error">{{col}}</div>
</div>
</div>
推荐阅读
- python - 如何在不影响其余部分的情况下延迟我的程序的一部分?
- javascript - 使用 JavaScript 按其类隐藏 li 的元素
- c++ - 模板问题
- vb.net - 如何限制一次产生的进程数?
- python - 在 Windows 上将 python 3.8 降级为 3.7 后如何在 PyCharm 中配置解释器?
- excel - 导出为 PDF 时,冻结的窗格会被部分裁剪
- java - 避免在 XML 中使用 Transformer 写入输出文件
- javascript - 如何在父组件中获取渲染的子组件?
- sql - 使用数据库中的数据更新 Excel 列表
- excel - 从 Excel 发送带有 pdf 附件的 Outlook 电子邮件并禁用 Outlook 附件上下文菜单