【发布时间】:2013-09-19 02:05:58
【问题描述】:
我有这个控制器:
JApp.controller('WebsiteController', function($scope, $resource) {
var UsersService = $resource('/auth/users', {});
$scope.adding = false;
$scope.users = [];
$scope.addUser = function() {
$scope.adding = true;
UsersService.query({}, function(data) {
$scope.users = data;
$scope.selectedUser = data[0];
});
}
$scope.cancelAddUser = function() {
$scope.adding = false;
}
});
我的 HTML:
<section class="vbox" ng-controller="WebsiteController">
<section class="panel animated fadeInDown">
<header class="panel-heading">
<h3>{{selectedUser.last_name}} </h3> <!-- Just to test I print it here -->
</header>
<div class="panel-body m-b">
<div class="row text-sm wrapper">
@if (role_admin())
<a href="{{{URL::action('WebsiteController@getAddWebsite')}}}" class="btn btn-sm btn-info"> <i class="icon-plus"></i> New Website </a>
@endif
</div>
<div class="table-responsive">
<table class="table table-striped b-t text-sm">
<thead>
<tr>
<th>URL</th>
<th>Assigned to</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- Outside this <tr> doesn't work -->
<tr ng-repeat="website in websites">
<td> {{website.url}}</td>
<td>
<span ng-repeat="assigned in website.users"> <span class="label label-info"> {{assigned.first_name}} </span> </span>
<a ng-click="addUser()" ng-hide="adding" class="btn btn-success btn-xs"> Add new </a></span>
<select ng-hide="!adding"
name="myselect"
ng-model="selectedUser"
ng-options="u.first_name for u in users">
</select>
<a href="#" ng-hide="!adding" ng-click="cancelAddUser()" class="btn btn-warning btn-xs">Cancel</a>
<input type="text" ng-model="selectedUser.first_name"> <!-- It works here! -->
</td>
<td>
<a href="#" class="btn btn-xs btn-white"> <i class="icon-pencil"></i> Edit </a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</section>
更新:请注意,它在我的<select> 旁边的<input> 中有效,但在我的<header> 中无效(仅绑定一次)
所以当我点击添加用户时,AJAX 调用将检索用户列表,并成功显示在<select> 中,默认情况下,selectedUser 将指向data[0],这是第一个用户。但是现在双向绑定现在绑定到data[0]。如果我将选择更改为其他用户,selectedUser 不会更新。但是如果我更新我的selectedUser,比如说名字,下拉列表中的名字也会改变。
我试过不使用这条线
$scope.selectedUser = data[0];
但仍然无法正常工作,尽管我指定了ng-model="selectedUser",但它根本没有绑定。
返回的 JSON:
[
{
"id": 1,
"role_id": 1,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "admin@admin.com",
"username": "admin",
"first_name": "Admin",
"last_name": "Istrator"
},
{
"id": 2,
"role_id": 2,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "johndoe@gmail.com",
"username": "john",
"first_name": "John",
"last_name": "Doe"
}
]
谁能帮我解决这个问题?如果没有必要,我会尽量不走 $digest 或 $apply 这条路。
更新 2 问题的根源是如果我尝试在上面的 HTML 中打印出以下 ng-repeat 之外的 selectedUser:
<tr ng-repeat="website in websites"> ...... </tr>
小提琴来说明我的问题:http://jsfiddle.net/jofrysutanto/4nfyV/3/
【问题讨论】:
-
你能提供来自查询的数据吗
-
您希望在更改下拉列表中选择的用户应该被更改
标签: javascript jquery ajax angularjs