angularjs的ng-show绑定不能在jQuery中工作

angularjs ng-show binding doesn't work with jQuery

本文关键字:jQuery 工作 不能 ng-show 绑定 angularjs      更新时间:2023-09-26

我有一些ng-repeat

<tr ng-repeat="Picture in Pictures">
    <td>{{Picture.Id}}</td>
    <td>
        <div ng-hide="Picture.editorEnabled">
            {{Picture.Name}}
        </div>
        <div ng-show="Picture.editorEnabled">
            <input ng-model="Picture.editName" class="form-control" ng-show="Picture.editorEnabled">
        </div>
    </td>
    <td>
        <button type="button" name="editButton" class="btn btn-warning" ng-hide="Picture.editorEnabled"
                ng-click="enableEditor(Picture)">Edit
        </button>
        <div ng-show="Picture.editorEnabled">
            <button type="button" name="saveEditButton" class="btn btn-success"
                    ng-click="saveEditor(editName,editImageUrl,Picture)">Save
            </button>
            <button type="button" name="cancelEditButton" class="btn btn-warning" ng-click="disableEditor(Picture)">
                Cancel
            </button>
        </div>
    </td>
</tr>
这里是我的控制器代码:
$scope.enableEditor = function(picture) {
    picture.editorEnabled = true;
    picture.editName      = picture.Name;
    picture.editImageUrl  = picture.ImageUrl;
};
$scope.disableEditor = function(picture) {
    picture.editorEnabled = false;
    picture.editName      = null;
    picture.editImageUrl  = null;
};
$scope.saveEditor = function(name, url, picture) {
    $.ajax({
        url: 'admin/pictures/edit/' + picture.Id,
        type: 'POST',
        data: {
            ImageUrl: url,
            Name: name
        },
        success: function() {
            picture.Name     = picture.editName;
            picture.ImageUrl = picture.editImageUrl;
            $scope.disableEditor(picture);
        }
    });
};

当我点击"编辑"出现编辑字段和保存,取消按钮。当我点击"取消",它就消失了。当我单击"保存"字段保存到DB时,方法disableEditor在同一对象上执行,我检查了Id属性,并在调试器中显示editorEnabled为假,但在我的浏览器中仍然存在保存,取消按钮和编辑字段。我再次点击"保存",它就消失了。

您应该尝试使用$http而不是$.ajax。jQuery的$.ajax在Angular的作用域之外执行。回调中的任何代码都不会反映在你的作用域中,因为它发生在Angular的摘要周期之外。试试下面的命令:

var url = 'admin/pictures/edit/' + picture.Id;
var data = $httpParamSerializerJQLike({
    ImageUrl: url,
    Name: name
});
var config = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
};
$http.post(url, data, config).then(function() {
    picture.Name     = picture.editName;
    picture.ImageUrl = picture.editImageUrl;
    $scope.disableEditor(picture);
});

要使其工作,您需要将$http$httpParamSerializerJQLike服务注入控制器。我假设您需要将此作为表单提交,因为这是$.ajax的默认工作方式。这需要Angular 1.4+。

注意,虽然可以使用$.ajax,然后用$timeout$scope.$apply()封装你的成功代码,但你最好使用Angular自己的$http

这不起作用,因为您在$scope.saveEditor中所做的一切都发生在angular之外(我假设$是jQuery)。这根本不是有棱角的方式。

你应该更深入地研究一下https://docs.angularjs.org/api/ng/service/$http这个angular HTTP服务,然后使用它。

每次使用非"angular方式"的东西时,都需要使用$apply,就像Anid已经提到的那样。

例如,如果你使用jQuery的http而不是angular的$http,你必须添加$scope.