angularjs启用/禁用指令上的按钮

时间:2015-03-05 16:31:12

标签: angularjs

我是Angular的新手,我已经坚持了一天。我有一个含有简单形式的指令拉出模态的内容。我想在提交表单时让最终用户不要双击。到目前为止,这是我得到的壁橱。内容和模态拉出正常,当单击按钮时它被禁用,ajax调用执行正常,模态再次隐藏,但按钮保持禁用状态。当我提到按钮时,我会参考模态内容上的按钮,其中id =“submitTradeForm”

这是模态中的内容

<div class="cdc-modal">

    @using (@Html.BeginForm("_CreateTrade", "Employees", FormMethod.Post, new { @class = "cdc-form", @id = "createTradeForm" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(null, new { @class="text-danger" })

        <div class="form-group">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @placeholder = "trade" })
        </div>

        <div class="modal-footer">
            <input id="submitTradeForm" type="button" ng-click="createTrade()" ng-disabled="isProcessing" class="btn cdc-button" value="Add new trade" />
        </div>
    }

</div>

这是JS / Angular代码

    //********************** ANGULARJS - BEGIN *****************************************//

    var app = angular.module('empApp',[]);

    app.controller('empCtrl', function ($scope) {

    });

    app.directive('empModal',function($compile){
        return {
            restrict: 'EA',
            templateUrl: '@Url.Content("~/Employees/_CreateTrade")',
            replace: true,
            controller: function ($scope) {

            },
            compile: function (tElement, tAttr) {

                var contents = tElement.contents().remove();
                
                var compiledContents;

                return function (scope, iElement, iAttr) {

                    if (!compiledContents) {
                        compiledContents = $compile(contents);
                    }

                    compiledContents(scope, function (clone, scope) {
                        iElement.append(clone);
                    });

                    scope.createTrade = function () {

                        scope.isProcessing = true;

                        var form = $("#createTradeForm");

                        $.ajax({
                            cache: false,
                            async: true,
                            type: "POST",
                            url: form.attr("action"),
                            data: form.serialize(),
                            success: function (data) {

                                $("#createTradeModal").modal("hide");

                                //empty the container
                                $("#trades").html("");

                                var sel = $("#trades");

                                var newCont = "";

                                for (var i = 0; i < data.length; i++) {
                                    sel.append('<option value="' + data[i].TradeId + '">' + data[i].Name + '</option>');
                                }

                                scope.isProcessing = false;
                            }

                        }).complete(function () {
                            scope.isProcessing = false;
                            console.log('completed');
                            console.log(scope.isProcessing);
                        });

                        
                        
                    };

                };

            }
        }
    });

    //********************** ANGULARJS - END   *****************************************//

这是在主视图

<div ng-app="empApp" ng-controller="empCtrl" class="container">
    <div class="row">
        <div class="col-sm-12">
            <h3>Add New Employee</h3>

            @using (Html.BeginForm("Create", "Employees", FormMethod.Post, new { @id = "createEmployeeForm"}))
            {
                    
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(null, new { @class="text-danger" })
                @Html.Hidden("selectedTrades", null, new { @id="selectedTrades" })

                <div class="row" style="margin-bottom:15px;">
                    <div class="form-group col-sm-12">
                        @Html.TextBoxFor(m => m.EmployeeNumber, new { @placeholder = "employee number", @class = "form-control pull-left col-sm-8" })
                        <span style="min-width:160px;margin-top:5px;" class="col-sm-4 cdc-text pull-left">last entered: @lastentered</span>
                    </div>
                </div>
                <div class="form-group">
                    @Html.TextBoxFor(m => m.FirstName, new { @placeholder = "first name", @class = "form-control", @id = "firstname" })
                </div>
                <div class="form-group">
                    @Html.TextBoxFor(m => m.LastName, new { @placeholder = "last name", @class = "form-control", @id = "lastname" })
                </div>
                <div class="form-group">
                    @Html.TextBoxFor(m => m.StoreAs, new { @placeholder = "store as", @class = "form-control", @id = "storeas" })
                </div>
                <div class="row" style="padding-bottom:15px;min-width:320px !important;">
                        <div id="selectContainer" class="col-sm-8 pull-left" style="max-width:280px;">
                            <select id="trades" multiple="multiple">

                                @if (Model.Trades.Any())
                                {
                                    foreach (CDCManagement.Trade trade in Model.Trades)
                                    {
                                        <option value="@trade.TradeId">@Html.Encode(trade.Name)</option>
                                    }
                                }
                            </select>
                        </div>
                        <a href="#" onclick="addTrade()" data-toggle="modal" data-target="#createTradeModal">
                            <span class="glyphicon glyphicon-plus cdc-icon col-sm-4 pull-left cdc-icon-push" style="padding-left:0;"></span>
                        </a>
                </div>
                <div class="form-group">
                    @Html.TextBoxFor(m => m.PhoneNumber, new { @placeholder = "phone number", @class = "form-control" })
                </div>
                <div class="form-group">
                    @Html.TextAreaFor(m => m.Comments, new { @placeholder = "comments", @class = "form-control" })
                </div>
                <div class="form-group">
                    <input id="createButton" type="button" onclick="processForm()" class="btn cdc-button" value="Add New Employee" />
                </div>
                    
            }

        </div>
    </div>

    <!-- modal begin (add title) -->
    <div class="modal fade" id="createTradeModal">
        <div id="modal-dialog" class="modal-dialog">
            <div id="modal-content" class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Add New Trade</h4>
                </div>
                <div id="modal-body" class="modal-body">
                    <emp-modal></emp-modal>
                </div>
            </div>
        </div>
    </div>
    <!-- modal end -->

</div>

1 个答案:

答案 0 :(得分:1)

你正在混合使用jQuery和angular,并且遇到了使用jQuery事件以角度触发某些内容的常见陷阱,在这种情况下是一个AJAX响应。

每当角度需要知道某些变化时,您需要触发$digest。网上有lots资源,我强烈建议您在编写更多代码之前先了解角度生命周期。

要解决您的问题,您应该只需更改以下行:

scope.isProcessing = false;

scope.$apply( function() { 
  isProcessing = false;
});

这告诉角度你正在改变它应该知道的东西,并且它运行它的摘要循环,相应地更新所有视图。这将重新启用您之前禁用的按钮。

顺便说一句:我不确定你是否正在重构现有的应用程序以使用角度,或从头开始。无论哪种方式,你应该尝试删除你对jQuery的依赖,除非有特定的原因。 This stackoverflow question是一个很好的参考,可以让你思考“角度方式”的事情。如果你能解决这个问题,那将会带来好处。