0

当对使用纯 JavaScript 表示的 DOM 元素进行更改时,我一直在尝试让 Angular JS 更新其模型。我不确定我是否只是没有正确编写我的 Angular JS 代码,或者我是否没有正确解决问题。

我有一个带有输入框的可排序列表,其中包含每个项目的排序值。您可以手动放置排序顺序,这将重新排序列表或拖放项目(使用 JQuery 可排序)。当您通过拖放对项目进行排序时,我会在 sortable 的更新回调函数中更新输入值,但这似乎并没有更新绑定到该输入的 Angular JS 对象。

我尝试包装我的 JS,它在 $scope.$apply 中操纵输入值,但它没有帮助。

这是一个小提琴:http: //jsfiddle.net/smelly_fish/d9kt9/1/

这是我的 JS:

var sortedShippingMethods = [{
    "id": "UPS 2nd Day Air A.M. ®",
    "name": "UPS 2nd Day Air A.M. ",
    "sort": "0"},
{
    "id": "UPS 3 Day Select ®",
    "name": "UPS 3 Day Select ",
    "sort": "0"},
{
    "id": "UPS Ground",
    "name": "UPS Ground",
    "sort": "2"}];

jQuery(document).ready(function(){

    // Sortable list
    $('#shipping-sort-list').sortable({
        items: 'li',
        axis: 'y',
        containment: 'parent',
        cursor: 'move',
        update: function(event, ui) {
            $scope = angular.element($('#shipping-sort-list')[0]).scope(); 
            $scope.$apply(function(){
                $('#shipping-sort-list input').each(function(i){
                    $(this).attr('value', i+1);
                });
            });
        }
    });
});

function AdminShippingSettingsCtrl($scope) {
    $scope.sortedShippingMethods = sortedShippingMethods;

    $scope.getSortValue = function(sortedShippingMethod) {
        //have to typecast to an int or 3 will show up higher than 23 (string sort ftl)
        var sort = parseInt(sortedShippingMethod.sort, 10);
        return sort;
    }
}​

这是我的标记:

<div id="shipping-sort-list" data-ng-app data-ng-controller="AdminShippingSettingsCtrl">
    <ul>
        <li data-ng-repeat="sortedShippingMethod in sortedShippingMethods | orderBy:[getSortValue, 'name']"><input data-ng-model="sortedShippingMethod.sort" type="text" name="sortOrder[{{sortedShippingMethod.id}}]" value="{{sortedShippingMethod.sort}}" /> {{sortedShippingMethod.name}}</li>
</ul>

<p data-ng-repeat="sortedShippingMethod in sortedShippingMethods">Name: {{sortedShippingMethod.name}} Sort Value: {{sortedShippingMethod.sort}}</p>
</div>
​
4

1 回答 1

1

如果你只是想要答案,你可以去:http: //jsfiddle.net/d9kt9/4/

有关解释,请继续阅读。当前迭代的问题是您正在更新元素的值,但实际上您需要更新每个 shippingMethod 的对象范围。该值只是一个来回传递的值(我知道很奇怪),但是如果您更新一个对象(就像我所做的那样),那么它是通过引用传递的,这允许您影响主要的 sortedShippingMethods。因此,虽然循环遍历它们是正确的做法,但您可以看到我是如何获得每个范围的:

$('#shipping-sort-list input').each(function(i){
    var inputScope = angular.element(this).scope();
    inputScope.sortedShippingMethod.sort = i+1;
});

然后在第二个列表的 data-ng-repeat 中,我添加了与第一个列表相同的 orderBy:

<p data-ng-repeat="sortedShippingMethod in sortedShippingMethods | orderBy:[getSortValue, 'name']">
于 2012-12-07T19:31:51.210 回答