我在表格中显示用户列表,每行的最后一列是按钮。单击该按钮时,会出现一个弹出窗口,可以编辑与所单击的行相关的用户。每个用户都有一个兴趣列表。在弹出窗口中,我有一个多选项,我想在其中显示用户当前的兴趣。当弹出窗口第一次出现时,它会获取正确的数据,但是当我尝试多次单击其他行时,数据保持不变。我知道这是因为ng-model
指令,那么解决这种情况的理想方法是什么?
这是我的多选
<select id="multipleSelect"
data-placeholder="Select interests..."
chosen
multiple
ng-model="$ctrl.activeInterests"
ng-options="interest for interest in $ctrl.interests"
style="width:370px; height:100px;">
<option value=""></option>
</select>
单击表格最后一列的按钮时,此功能称为
this.editButtonClicked = function(tableRowUser) {
$scope.firstName = tableRowUser.firstName;
$scope.lastName = tableRowUser.lastName;
$scope.email = tableRowUser.email;
$scope.role = tableRowUser.role;
$scope.tag = tableRowUser.tag;
$scope.username = tableRowUser.username;
// Fetch the active interests
fetchInterests($scope.tag);
// Fetch the available interests the user can choose
fetchAllAvailableInterests();
// After this, make the Edit Form visible
togglePopupClass();
}
在'fetchInterests'函数中,我将绑定到ng-model的数据再次清空,但没有任何成功。
function fetchInterests(newInterests) {
self.activeInterests = []; // <- Here I make it empty
var interests = newInterests.split('|');
for (i = 0; i < interests.length; i++) {
// Trim the excess whitespace.
var tag = interests[i].replace(/^\s*/, "").replace(/\s*$/, "");
self.activeInterests.push(tag);
}
}
官方文档说ng-model
只有在分配给一个全新的对象或集合时才会重新呈现。我也试过这个,但没有任何成功。
答案 0 :(得分:0)
很遗憾,我无法根据您提供的代码告诉您解决方案的错误。
这是一个快速演示,可以帮助您解决问题。
// Code goes here
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope){
$scope.allInterests = ['Cars', 'Football', 'Fishing', 'Pets', 'Cooking'];
$scope.users = [
{
name: 'Bob',
age: 34,
interests: ['Cars', 'Football']
},
{
name: 'Mary',
age: 33,
interests: ['Pets', 'Cooking']
}
];
$scope.showDetails = function(user){
$scope.selectedUser = user;
};
}]);
&#13;
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="user in users">
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td><button ng-click="showDetails(user)">Show interests</button></td>
</tr>
</table>
<hr>
Editing: {{selectedUser.name}} <br>
Age: {{selectedUser.age}} <br>
<select multiple ng-model="selectedUser.interests" ng-options="interest for interest in allInterests"></select> <br>
Selected interests: {{selectedUser.interests.join(',')}}
</body>
</html>
&#13;