javascript - 在 AngularJS 中编辑表单时,如何使用 "map"模型值来选择框?

标签 javascript angularjs

我正在 AngularJS Controller 中通过查询获取数据:

$scope.customers = xAccount.query();

我使用选择框来显示包含客户数据的下拉项:

<select type="text"
    data-ng-model="mymodel.customer_id"
    data-ng-options="customer.id as customer.name for customer in customers track by customer.id">
</select>

$scope.customers显示的数据是这样的:

[
    {"id":"12345678","name":"first customer"},
    {"id":"23456789","name":"second customer"},
    {"id":"34567890","name":"third customer"}
]

我使用的 $scope 模型是:

mymodel.customer_id

现在,我能够通过API调用获取所有客户,将其名称作为选择标签和ID作为SELECT值,然后将选定的标签作为Ojit_code保存到数据库中。这工作得很好。

“编辑” View /表单不起作用。当显示编辑表单(与"new"表单相同)时,选择框获取的值为空。这意味着 select.value = mymodel.customer_id 已设置(我可以在 firebug 的 JSON 显示中将其视为类似“12345678”的字符串),但它并未“附加”到表单的 mymodel.customer_id 上。我怎样才能实现这一目标?

我尝试使用select.value,但当然会失败。

最佳答案

我之前遇到过类似的问题,我所做的修复是填充 $scope.customers首先,然后填充 mymodel.customer_id 中的值.

所以基本上,您必须首先通过 $scope.customers = xAccount.query(); 吸引所有客户当您打开编辑表单时,您可以使用该表单的 promise 成功回调来提取您的客户详细信息。

我没有时间深入研究这个问题,但这对我有用。

考虑xAccount$resource 的一个实例使用 GET 请求:

$scope.editCustomer = function() {     // Or whatever is your function when your edit form opens

    // First get all the customers
    $scope.customers = xAccount.query(null, function() {
        // When you successfully get your customer data (success callback)
        // Now here you have to make another call to get your customer
        $scope.mymodel = MyModel.get({id: $routeParams.id});
    });
};

现在,我想说的是,当您打开编辑表单时(我正在考虑调用 editCustomer() 方法,该方法首先获取所有客户数据。从服务器收到客户数据(并绑定(bind)到 HTML 中的 select ),那么只有我们才能使用 MyModel 获取正在编辑的客户的数据。

关于javascript - 在 AngularJS 中编辑表单时,如何使用 "map"模型值来选择框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34132040/

相关文章:

javascript - AngularJS - $compile 不是一个函数

javascript - 在 pdfmake 中使用 dataUrl 时出现无效图像错误

javascript - 我的 ajax 请求提交一次,然后提交两次,然后提交 4 次并不断加倍

javascript - 重新绑定(bind)位于 'ng-click' 中的 'ng-view' 指令

javascript - 是否可以在我自己的项目中使用另一个包中的 npm 依赖项?

Angularjs - Controller 继承与范围继承

json - 使用 AngularJS 获取 JSON 数据并在返回对象上添加方法

javascript - Angular .js : how to get rendered text width from directive?

javascript - 在 CSS3D 元素上查找屏幕坐标的局部坐标

javascript - 使用 JavaScript 对象更改 element.style